The installation

npm install axios;

The introduction of

I usually create a request folder in the project’s SRC directory, and then create an http.js and an api.js file inside. The http.js file is used to wrap our AXIos, and the api.js file is used to unify our interfaces.

// Introduce axios in http.js

import axios from ‘axios’; / / introduce axios

// Environment switch

if (process.env.NODE_ENV == ‘development’) { axios.defaults.baseURL = ‘www.baidu.com’; } else if (process.env.NODE_ENV == ‘debug’) { axios.defaults.baseURL = ‘www.ceshi.com’; } else if (process.env.NODE_ENV == ‘production’) { axios.defaults.baseURL = ‘www.production.com’; } / / copy

Setting request Timeout

Set the default request timeout with axios.defaults.timeout. For example, if the request exceeds 10s, the system notifies the user that the request has timed out and needs to be refreshed.

axios.defaults.timeout = 10000; / / copy

Setting of the POST request header

For post requests, we need a header, so we can set the default header for post to Application/X-www-form-urlencoded; charset=UTF-8

axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded; charset=UTF-8’; / / copy

Request to intercept

Import store from ‘@/store/index’; import store from ‘@/store/index’;

/ / request interceptor axios. Interceptors. Request. Use (config = > {/ / whether there is in every time before sending a request to judge vuex token / / if it exists, is unified in the HTTP request header and token, Const token = store.state.token; const token = store.state.token; token && (config.headers.Authorization = token); return config; }, error => { return Promise.error(error); }) copy the code

Generally, after login, the user’s token is stored locally through localStorage or cookie. Then when the user enters the page (i.e. in main.js), the user will first read the token from the localStorage. If the token exists, the user has logged in. Then update the token status in the VUEX. Then, each time you request an interface, you will carry a token in the header of the request, and the background staff can judge whether your login is expired according to the token you carry. If you do not carry the token, it indicates that you have not logged in. Each request carries a token, so what if a page can be accessed without user login? In fact, your front-end request can carry token, but the background can choose not to receive ah!

// Response interceptor

Axios. Interceptors. Response. Use (response = > {/ / if the returned a status code of 200, that interface request is successful, If (response.status === 200) {return promise.resolve (response); } else { return Promise.reject(response); }}, // The server status code does not start with 2 // here can be your background developers to negotiate a unified error status code // then according to the returned status code some operations, such as login expiration message, error message and so on // here are some common operations. Error => {if (error.response.status) {switch (error.response.status) {// 401: If you do not log in // If you do not log in, the login page is displayed and the path of the current page is displayed. // If you successfully log in to the current page, you need to perform this step on the login page. case 401: router.replace({ path: '/login', query: { redirect: router.currentRoute.fullPath } }); break; Case 403: Toast({message: 'Login expired, please log in again ', duration: 1000, forbidClick: true }); // Remove token localstorage. removeItem('token'); store.commit('loginSuccess', null); SetTimeout (() => {router.replace({path: '/login', query: {redirect: router.currentRoute.fullPath } }); }, 1000); break; // 404 request not found case 404: Toast({message: 'Network request not found ', duration: 1500, forbidClick: true}); break; / / other errors, directly thrown error default: Toast ({message: error. The response. The data message, duration: 1500, forbidClick: true}); } return Promise.reject(error.response); }}}); Copy the codeCopy the code

A response interceptor is the data that the server sends back to us and we can do something with it before we get it. For example, the above idea: if the status code returned by the background is 200, the data will be returned normally; otherwise, some errors we need will be made according to the type of the status code of the error. In fact, this is mainly an operation of unified processing of errors and adjusting the login page after no login or expiration of the login.

Note that the Toast() method above is the Toast light prompt component in the Vant library that I introduced, and you use one of your prompt components, depending on your UI library.

Encapsulate get and POST methods

Wrap the GET method

/** * get method, * @param {String} url * @param {Object} params params){ return new Promise((resolve, reject) =>{ axios.get(url, { params: params }).then(res => { resolve(res.data); }).catch(err =>{ reject(err.data) }) }); } Duplicate codeCopy the code

To encapsulate the post

/** * post method, * @param {String} url * @param {Object} params */ export function post(url, params) { return new Promise((resolve, reject) => { axios.post(url, QS.stringify(params)) .then(res => { resolve(res.data); }) .catch(err =>{ reject(err.data) }) }); } Duplicate codeCopy the code

The encapsulation of Axios is almost complete.