- background
- I usually use Axios to make requests in Vue projects. When I used Axios for self-study, I used the following method, which was very inelegant
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(); }); Copy the code
- After work, under the guidance of the master, I learned this method, so record it
- Start by wrapping a Request.js API
import axios from 'axios'
import utilHelper from '.. /utilHelper';
import {
Notify
} from "vant";
// Create an axios instance
const request = axios.create({
baseURL: utilHelper.scope.proxyName, / / API base_url
//timeout: 5000 // Request timeout period
headers: {
'content-type': 'application/json'}});// The request interception layer adds a token to the request header for each request
request.interceptors.request.use(function (config) {
let token = utilHelper.scope.token; // Get the token of the storage
if(token ! = =' ') {
// Put the token in the request header to the server and the Tokenkey in the request header
config.headers.token = token;
// It can also be written this way
// config.headers['accessToken'] = Token;
}
return config;
}, function (error) {
return Promise.reject(error);
});
// Response interception
request.interceptors.response.use(function (response) {
// Intercepting an error request and the backend convention that result equals zero is an exception request
if(response.data.result ! =1) {
// Error popup
Notify({
message: response.data.data,
duration: 3000.background: "#fa4049"
});
if (response.data.data == 'Invalid Key') {
window.location.href = "./index.html#/login";
}
throw Error(response.data.result); // Throw an error
}
return response;
}, function (error) {
// Do something with response error
if(error.response.status == 401){
Notify({
message: "Please log in first.".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;
Copy the code
- You then need to import the above files into the organization request Api file
- Such as loginApi. Js
import request from "@/apis/common/request.js";
/** * login *@param {*} account
* @param {*} pwd
*/
const login = function (account, password) {
return request({
method: "POST".url: '/user/login'.params: {
account,
password
}
}).then(resp= > {
return resp.data;
});
}
export default {
login
}
Copy the code
- Import in the file that needs to use the request Api and use try catch async await
import loginApi from "@/apis/login/loginApi";
try {
// Initiate a request
let { data : result } = await loginApi.login(this.account, this.pw);
// The token is stored after the login
} catch (err) {
} finally{}Copy the code
- About utilsHelper. Js
- It is mainly used to store some edible data in memory, such as token and proxyName(the base path of AXIos request)
let scope = { proxyName: process.env.NODE_ENV == "production" ? ".. /" : ". /".// Request paths are different in development and production environments and can be set after communication with the back end } Copy the code
- Vue.config.js for the agent Settings
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
}
// Do not change the image to base64
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
}
Copy the code