一、js文件
1.1 引入axios
import axios from 'axios'
1.2 引入api文件
import 自定义(如:service) from '路径'
二、配置axios
2.1 创建axios实例
let instance=axios.create({
baseURL:'http://124.71.187.212:9008/api', //后端服务名
timeout:1000 //请求时长(不写默认1000)
})
2.2 请求 格式 / 参数 统一
const Http={ };
for (let key in service){
let api = service[key]; //url method
Http[key] = async function(
params, //请求参数 get delete:url, put post patch :data,
isFromData=false, //是否位from-data请求
config={ } //配置参数
){
let newParams={}
//content-type 是否是from-data 的判断
if(params && isFromData){
newParams=new FromData()
for(let i in params){
newParams.append(i,params[i])
}
}else{
newParams=params
}
//不同请求的判断·
let response={}
if(api.method=='put' ||api.method=='post' ||api.method=='patch'){
try{
await instance[api.method](api.url , newParams , config)
}catch(err){
response = err
}
}else if(api.method=='get' || api.method=='delete'){
config.params=newParams
try{
response=await instance[api.method](api.url , config)
}catch(err){
response=err
}
}
return response; //返回响应值
}
2.3 添加拦截器
2.3.1 请求拦截器
axios.interceptors.request.use(config=>{
//在发送请求前做些什么
return config
},err=>{
//响应失败做些什么
return Promise.reject(err)
})
2.3.2 响应拦截器
axios.interceptors.response.use(res=>{
//请求成功
return response.data
},err=>{
//请求失败
console.log(err)
return Promise.reject(response.data)
})
export default Http
三、把Http挂载到vue实例上
3.1 在main.js里导入
import Http from '文件路径'
//把Http挂载到vue实例上
Vue.prototype.$Http=Http