import axios from 'axios';
import vMessage from '@/components/messageTips';
import qs from 'qs';
import router from '@/router';
const service = axios.create({
// 请求超时时间
// timeout: 3000
});
// 解决跨域时的OPTION请求
service.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// 请求拦截器
service.interceptors.request.use(
async config => {
return config;
},
err => {
console.log(err);
}
);
service.interceptors.response.use(
response => {
if (response.status === 200) {
return response;
} else if (response.status === 207) {// 自己项目中的特殊错误码,可忽略
router.push({
name: 'login',
query: {
redirectUrl: location.href
}
});
}
},
err => {
return Promise.reject(err.request);
}
);
const asyncGet = (url, params, config, errorExt) => {
const obj = Object.assign({
url: `${window.projectConfig.url}/${url}`,
method: 'get',
params
}, config);
return to(service(obj), errorExt);
};
const asyncDownload = (url, params, config, errorExt) => {
const obj = Object.assign({
url: `${window.projectConfig.url}/${url}`,
method: 'get',
params,
responseType: 'arraybuffer'
}, config);
return to(service(obj), errorExt);
};
const asyncPost = (url, data, config, errorExt) => {
const obj = Object.assign({
url: `${window.projectConfig.url}/${url}`,
method: 'post',
data: qs.stringify(data)
}, config);
return to(service(obj), errorExt);
};
const asyncPut = (url, data, config, errorExt) => {
const obj = Object.assign({
url: `${window.projectConfig.url}/${url}`,
method: 'put',
data: qs.stringify(data)
}, config);
return to(service(obj), errorExt);
};
const asyncDelete = (url, params, config, errorExt) => {
const obj = Object.assign({
url: `${window.projectConfig.url}/${url}`,
method: 'delete',
params
}, config);
return to(service(obj), errorExt);
};
const to = (promise, errorExt = '未知错误') => {
return promise
.then(function (data) {
return [null, data];
})
.catch(function (err) {
if (errorExt) {
Object.assign(err, { errorExt });
}
vMessage.error(`${err.errorExt} [ code:${err.status} ]`);
return [err, undefined];
});
};
const exportObj = {
service,
to,
asyncGet,
asyncPost,
asyncPut,
asyncDelete,
asyncDownload
};
export default exportObj;
使用
1、main.js中定义全局axios
import selfAxios from '@/api/axiosConfig';
Vue.prototype.$http = selfAxios;
2、配合async/await
async login () {
const [err, res] = await this.$http.asyncGet('api/v1.0/login', params);
if (!err && res) {
if (res.data.success) {
...
} else {
...
}
}
}