以下是我的写法,有意见的可以随时提出
首先建立相应文件夹
api.js请求方式封装
import axios from 'axios';
axios.defaults.timeout = 60000
axios.defaults.baseURL = '/'
//对返回错误信息进行的处理
import judgeErrorCode from './errorCode.js'
// 添加请求拦截器(目前并不完善)
//axios.interceptors.request.use(config => {
// config.headers.Authoriation = window.sessionStorage.getItem('token');
// config
// return config
})
// 添加响应拦截器
axios.interceptors.response.use(function (res) {
// 对响应数据做点什么
// 由于状态码没有用http的状态码,全部是后端随性而来,哎~所以状态码返回在res.data里面
// 这里的状态码可根据实际情况来修改
if(res.data.code=='200'){
return Promise.resolve(res);
}else {
if(res.data.code == 401) {
//跳转到登录页面(还需优化)
var url = window.location.href;
var ut=""
ut= url.split("#");
var u=""
u=ut[0];
window.location.href=u;
}
// judgeCode详情看errorCode文件
judgeErrorCode(`code${res.data.code}`, res.data.message)
return Promise.reject(res);
}
}, function (error) {
// 断网 或者 请求超时 状态
if (!error.response) {
// 请求超时状态