Vue中的axios请求封装
程序员文章站
2022-07-02 12:32:48
...
在发送axios请求时,如果每个组件都需要各自发送的话,那么代码太过冗余。
所以可以将请求方法进行封装。
创建ajax.js用于处理各种请求方式:
import axios from 'axios';
// import {Decrypt} from '../../static/js/utils.js'
const env = process.env.NODE_ENV;
// timeout 10min
const Global_Delay = 10 * 60 * 1000;
const BASE_URL = 'http://127.0.0.1:9898';
// 定义一个空的数组,用于存放请求中的参数
// 创建axios实例
const axiosInstance = () => {
const instance = axios.create({
baseURL: BASE_URL,
timeout: Global_Delay,
});
return instance;
};
// 请求实例
const publicReq = async params => {
const { url, method, param } = params;
const instance = axiosInstance();
return await instance({
url,
method,
// 在请求头里面添加token 如果没有则为空字符串
headers :{
'token' : localStorage.getItem('token') === null ? '' : localStorage.getItem('token')
},
[method === 'post' ? 'data' : 'params']: param || {},
transformRequest: [function (data) {
let ret = ''
let index = 0;
for (let key in data) {
if (data[key] === null) {
ret += `${index === 0 ? '' : '&'}key=&`
} else {
ret += `${index === 0 ? '' : '&'}${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
}
index += 1;
}
return ret
}]
}).then(res => {
if (res) {
if (res.status !== 200) {
throw new Error(res.statusText);
}
return res;
}
});
};
// 请求超时函数
const timeoutfn = (delay, url) => {
return new Promise(resolve => {
setTimeout(() => {
resolve('请求超时');
}, delay);
});
};
// 单个请求 存在请求超时
export async function req(params, delay = Global_Delay) {
try {
const response = await Promise.race([
timeoutfn(delay, params.url),
publicReq(params),
]);
if(response.data.code === 401){
// this.$message.error(response.data.message);
localStorage.removeItem("token");
sessionStorage.removeItem("adminLogin");
location.href = '/';
}
return response;
} catch (error) {
throw new Error(error);
}
}
// GET request
export async function getRequest(url, param) {
try {
const response = await req({
url,
method: 'get',
param,
});
return response;
} catch (err) {
// 这里走本地模拟数据
console.log(err);
}
}
// POST request
export async function postRequest(url, param) {
try {
const response = await req({
url,
method: 'post',
param,
});
return response;
} catch (err) {
console.log(err);
}
}
创建index.js封装方法:
/**
* 包含n个接口请求函数的模块
*/
import { getRequest, postRequest } from './ajax.js';
export default {
$$path: {
getdictionarybytypecode: '/dicmodule/dic/typecodelist',
getcarassess: '/dicmodule/car/assess',
getuserregister: '/usermodule/user/register',
getuserlogin: '/usermodule/user/login',
changepassword: '/usermodule/user/changepwd',
getuserinfo: '/usermodule/user/info',
updateuserinfo: '/usermodule/user/edit',
getusercheckreal: '/usermodule/user/checkreal',
getcarinsert: '/carmodule/car/insert',
getDictionaryBytypecode: '/dicmodule/dic/list',
getallcarslist: '/carmodule/car/list',
getcarbysometype: '/carmodule/car/typelist',
getcarinfo: '/carmodule/car/carinfo',
getorderadd: '/ordermodule/order/insert',
getuserownercar: '/usermodule/user/getowncar',
getuserorder: '/usermodule/user/getorders',
getuserlook: '/ordermodule/order/userlook',
getuserpay: '/ordermodule/order/userpay',
getsellersure: '/ordermodule/order/sellersure',
getordercancel: '/ordermodule/order/cancel',
},
getDicBytypeCode(params) {
return getRequest(this.$$path.getdictionarybytypecode, params);
},
getDicAssess(params) {
return postRequest(this.$$path.getcarassess, params);
},
getUserRegister(params) {
return postRequest(this.$$path.getuserregister, params);
},
getUserLogin(params) {
return postRequest(this.$$path.getuserlogin, params);
},
getUserPwdChange(params) {
return postRequest(this.$$path.changepassword, params);
},
getUserInfo(params) {
return getRequest(this.$$path.getuserinfo, params);
},
getUserUpdate(params) {
return postRequest(this.$$path.updateuserinfo, params);
},
getUserCheckReal(params) {
return getRequest(this.$$path.getusercheckreal, params);
},
getCarInsert(params) {
return postRequest(this.$$path.getcarinsert, params);
},
getDictionaryBytypecode(params) {
return getRequest(this.$$path.getDictionaryBytypecode, params);
},
getAllCarsList(params) {
return getRequest(this.$$path.getallcarslist, params);
},
getCarbySometype(params) {
return getRequest(this.$$path.getcarbysometype, params);
},
getCarInfo(params) {
return getRequest(this.$$path.getcarinfo, params);
},
getOrderAdd(params) {
return postRequest(this.$$path.getorderadd, params);
},
getUserOwnCar(params) {
return getRequest(this.$$path.getuserownercar, params);
},
getUserOrders(params) {
return getRequest(this.$$path.getuserorder, params);
},
getUserLook(params) {
return postRequest(this.$$path.getuserlook, params)
},
getUserPay(params) {
return postRequest(this.$$path.getuserpay, params)
},
getSellerSure(params) {
return postRequest(this.$$path.getsellersure, params)
},
getCancelorder(params) {
return postRequest(this.$$path.getordercancel, params)
}
};
上一篇: Vue异步请求(axios)
下一篇: axios异步请求总结