1.在src目录下创建一个http文件夹
新建index.js和requst.js两个js文件
index.js中封装请求接口的的方法,代码如下:
import axios from "axios";
var instance = axios.create({
baseURL:'xxxxx(接口)',
timeout:3000,
})
instance.interceptors.request.use(
config =>{
localStorage.token&&(config.headers.Authorization = localStorage.token)
return config
},
error=>{
return Promise.error(error)
}
)
axios.interceptors.response.use(response =>{
return response
},error=>{
return error
}
)
export const httpServe = (path,params={},method='get',data={})=>{
return new Promise((resolve,reject)=>{
instance({
method,
url:path,
data,
params
})
.then(res=>{
resolve(res)
})
.catch(err=>{
reject(err)
})
})
}
requst.js文件封装调用接口的方法
import { httpServe } from '@/http/index.js';
//登录
export const loginPost = (path,data)=>httpServe(path,{},'post',data)
2.使用
首先在需要使用的组件中引用requst中的方法
import {loginPost} from '@/http/requst.js'
然后直接把方法拿过来使用即可,方法传参首先是接口的地址,然后是参数
loginPost('login',{
username:this.ruleForm.username,
password:this.ruleForm.password
})