This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

This article was written in July 2018. At that time, I was preparing to change the framework. I used jQuery $. Ajax before, and after switching to Vue, I planned to use axiOS as the network request library, which was officially recommended. Speed up access and reduce server-side stress.

In the process of using the initial exploratory version, we need to deal with the network request to pull data from the server side, and use AXIOS instead of $. Ajax. Please note the problems encountered and the solutions.

Related documents Official documents Interception + Route redirect Demo

Q: User login information. Each request requires parameters, which are cumbersome to use and prone to errors. All request paths are preprocessed

A: Using the default configuration, this data is carried with each request

axios.defaults.data = {
  uid: localStorage.uid,
};
Copy the code

Set the baseURL

axios.defaults.baseURL = '/api';
Copy the code

Q: Different parameters are used for get and POST. Params is used for GET and data is used for POST

A: Use an interceptor to intercept the request before it is sent, process parameters uniformly, and assign data to Params if it is get

Q: The default post mode is JSON, and the current background recognition format is Application/X-www-form-urlencoded

A: Use qs.stringify to process data and send it in the request interceptor as recommended

axios.interceptors.request.use((config) => {
  // Do something before request is sent
 if (config && config.data) {
    config.data = qs.stringify(config.data);
 }
  return config;
}
Copy the code
Q: During service development, some request data does not change, but is frequently used. You want to cache some specified requests locally. Next time a request with the same parameters is invoked, the local cache data is directly returned instead of being obtained from the server

A: A layer of encapsulation is made to AXIos. The URL + parameters of the request to be cached are processed into A string as A key and stored in sessionStorage. When the request is met again, the data will be returned from sessionStorage preferentially

Finally form the overall configuration

import Vue from 'vue'; import axios from 'axios'; import qs from 'qs'; import bzt from '@/utils/bzt'; axios.defaults.baseURL = ''; if (process.env.NODE_ENV ! == 'production') { axios.defaults.baseURL = '/api'; } const config = { }; const urlParam = bzt.getParam(); / * * * axios encapsulation, with the function of the local cache axios, request parameters must be put in the data at the same time, Specification * @ url param config configuration items * @ return {Promise < unknown >} | * * / const likeAxios = (config) = > {the if (config. Url && config.url.includes('? ')) {throw SyntaxError(' The URL must exist and cannot be included? Characters'); } let cacheData = null; config.data = config.data || {}; if (! config.withoutOtherParam) { config.data.isAjax = true; } config.urlJson = `${config.url}? ${qs.stringify(config.data)}`; if (config.cache && window.sessionStorage) { cacheData = window.sessionStorage.getItem(config.urlJson); config.data.__cache = { urlJson: config.urlJson, } } if (cacheData) { return getCacheData(config, cacheData); } else { return _axios(config); }}; @param cacheData * @return {Promise<unknown>} */ const getCacheData = (config,  cacheData) => { return new Promise ((resolve, reject) => { let data = null; try { data = JSON.parse(cacheData); } catch (e) { window.sessionStorage.removeItem(config.urlJson) } if (data) { resolve(data); } else { _axios(config) .then((result) => { resolve(result); }) .catch((e) =>{ reject(e); }); }}); }; const _axios = axios.create(config); _axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; _axios.interceptors.request.use( (config) => { // Do something before request is sent if (config) { config.data = config.data || {}; if (config.data.__cache) { config.__cache = config.data.__cache; delete config.data.__cache; } if (config.method === 'get') { config.params = config.data; } else if (! config.formData) { config.data = qs.stringify(config.data); } } return config; } , error => // Do something with request error Promise.reject(error), ); _axios.interceptors.response.use((response) => { // Do something with response data if (response && response.data) { // Code === 4 if (! response.config.noRedirect && window.location.hostname ! == 'localhost' && ! response.data.success && response.data.code ! == undefined && response.data.code === 4) { if (window.sessionStorage) { window.sessionStorage.setItem('goto', window.location.href); } window.location = '/web_pc/login.html'; } return response.data; } return response; }, error => // Do something with response error Promise.reject(error)); Plugin.install = function (Vue, options) { Vue.axios = likeAxios; window.axios = likeAxios; Object.defineProperties(Vue.prototype, { axios: { get() { return likeAxios; }, }, $axios: { get() { return likeAxios; ,}}}); }; Vue.use(Plugin); export default Plugin;Copy the code