Introduction to axios:
axios is a popular front-end Library in recent years. It perfectly replaces ajax in jquery. It can run not only in browser but also in nodejs environment. It also supports Promise API, which can intercept requests and return And naturally resistant to XSRF
Why encapsulation is needed:
Sometimes we need to handle the status of the server uniformly. If the status code returned by the server is 300, we need to redirect to the login page. At this time, we can encapsulate the api of axios to handle our 300 status code uniformly. In short, the encapsulation is to make the program more concise and easy to modify Reduce repetitive work
Benefits and purpose of packaging:
Errors can be handled uniformly
Status codes can be processed uniformly
Make it easier to call
It can better meet the needs of the project
Preparation for packaging, key points and difficulties:
The status code needs to be agreed with the background developer
The request expiration time for the project needs to be determined
Callback saving mechanism, session, cookie, token
What request methods are needed
What format, json, formdata, or url splicing parameters are required
Here, you need to pay attention to some api parameters of axios
When the method is get, the parameter is params
When the method is post, the parameter is data
If the withCredentials parameter is true, cross domain authentication is supported
In addition, you can cancel an already initiated xhr request
In addition, when encapsulating axios, we may introduce other third-party libraries, such as pop-up plug-ins, vuex, and router jump
Full code:
Put an axios package used in our project
import router from '../router' import axios from 'axios' import config from './config' // The api base address of the axios default configuration request axios.defaults.baseURL = (process.env.NODE_ENV !== 'production' ? config.dev.httpUrl : config.build.httpUrl) // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' axios.defaults.timeout = 30000 // Timeout setting 30s export default ((url = '', data = {}) => { return { get (url, data) { return new Promise((resolve, reject) => { axios.get(url, { withCredentials: false, params: data }).then(function (response) { if (response.data.status === 1101) { router.push({path: '/login'}) } else if (response.data.status === 200) { resolve(response.data) } else { resolve(response.data) } }).catch(function (error) { reject(error) }) }) }, post (url, data) { return new Promise((resolve, reject) => { axios.post(url, data, { withCredentials: false // headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} }).then(function (response) { if (response.data.status === 1101) { router.push({path: '/login'}) } else if (response.data.status === 200) { resolve(response.data) } else { resolve(response.data) } }).catch(function (error) { reject(error) }) }) } } })()
Another way of writing
import axios from "axios"; var service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url // withCredentials: true, // send cookies when cross-domain requests timeout: 5000 // request timeout }); // Add request interceptor service.interceptors.request.use( function(config) { // What to do before sending the request return config; }, function(error) { // What to do about request errors return Promise.reject(error); } ); // Add response interceptor service.interceptors.response.use( function(response) { // Do something about the response data return response; }, function(error) { // Do something about response errors return Promise.reject(error); } ); export default service;
Summary:
Many libraries on the Internet can be used, but experts should not only meet the needs, but also transform them to adapt to their own projects So as to improve the development efficiency Easy to use effect