- 背景
- 平时在Vue项目中经常使用的axios进行请求,之前在自学时,使用axios用的是以下方法,十分不优雅
this.axios({
method: "GET",
url: "/xxx/xxx",
params
})
.then(res => {
this.$toast.clear();
if(res.status == 200){
this.xxxx = res.data.xxxx.xxxx.concat([]);
}
})
.catch(err => {
this.$toast.clear();
});
- 工作后,在师傅的指导下,学会了这种方法,故记录一下
- 首先封装一个request.js api
import axios from 'axios'
import utilHelper from '../utilHelper';
import {
Notify
} from "vant";
const request = axios.create({
baseURL: utilHelper.scope.proxyName,
headers: {
'content-type': 'application/json'
},
});
request.interceptors.request.use(function (config) {
let token = utilHelper.scope.token;
if (token !== '') {
config.headers.token = token;
}
return config;
}, function (error) {
return Promise.reject(error);
});
request.interceptors.response.use(function (response) {
if (response.data.result != 1) {
Notify({
message: response.data.data,
duration: 3000,
background: "#fa4049"
});
if (response.data.data == '无效的Key') {
window.location.href = "./index.html#/login";
}
throw Error(response.data.result);
}
return response;
}, function (error) {
if(error.response.status == 401){
Notify({
message: "请先登录",
duration: 3000,
background: "#fa4049"
});
window.location.href = "./index.html#/login";
}else{
Notify({
message: error.message,
duration: 3000,
background: "#fa4049"
});
return Promise.reject(error);
}
});
export default request;
- 之后再需组织请求Api的文件中引入上面的文件
- 如loginApi.js
import request from "@/apis/common/request.js";
const login = function (account, password) {
return request({
method: "POST",
url: '/user/login',
params: {
account,
password
}
}).then(resp => {
return resp.data;
});
}
export default {
login
}
- 在需使用请求Api的文件中引入,并使用try catch async await
import loginApi from "@/apis/login/loginApi";
try {
let { data : result } = await loginApi.login(this.account, this.pw);
} catch (err) {
} finally {
}
let target = "http://xxx.xxxx.xxx";
let appNameList = ['/user', '/ddd', '/aaa', '/xxxx', '/xxxxxx'];
let proxyObj = {};
appNameList.forEach(name => {
proxyObj[name] = {
target,
changeOrigin: false
}
});
module.exports = {
devServer: {
historyApiFallback: true,
noInfo: true,
port: 8080,
proxy: proxyObj
}
chainWebpack: config => {
config.module
.rule('images')
.use('url-loader')
.loader('url-loader')
.tap(options => {
options.limit = -1
return options
})
},
publicPath: './',
outputDir: undefined,
assetsDir: undefined,
runtimeCompiler: undefined,
productionSourceMap: false,
parallel: undefined,
css: undefined
}