Vue uses Axios detailed process

1. Installation

Use npm:

npm install axios

Or use yarn:

yarn add axios

2. Configure Axios

Create a new axios.js file in the src/plugins directory, and customize axios in the file, as shown below:

 All codes of axios.js:

"use strict";

import Vue from 'vue';
import axios from "axios";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
axios.defaults.headers.common['Authorization'] = `Bearer ${"inittoken"}`;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  timeout: 60 * 1000, // Timeout
  withCredentials: false, // `withCredentials` 表示跨域请求时是否需要使用凭证
  responseType: 'json', // 默认值 `responseType` 表示浏览器将要响应的数据类型 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream' 浏览器专属:'blob'
  responseEncoding: 'utf8', // 默认值 `responseEncoding` 表示用于解码响应的编码 (Node.js 专属) 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求 Note: Ignored for `responseType` of 'stream' or client-side requests
  xsrfCookieName: 'XSRF-TOKEN', // 默认值  `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值  `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称 
  onDownloadProgress: (progressEvent) => {
    // 处理原生进度事件 `onDownloadProgress` 允许为下载处理进度事件  浏览器专属
    return progressEvent
  },
  maxContentLength: 2000, //`maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
  maxBodyLength: 2000,// `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
  validateStatus: (status) => {
    // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
    // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
    // 则promise 将会 resolved,否则是 rejected。
    return status >= 200 && status < 300; // 默认值
  },
  maxRedirects: 5, // 默认值 `maxRedirects` 定义了在node.js中要遵循的最大重定向数。如果设置为0,则不会进行重定向
};

const _axios = axios.create(config);
//request 拦截器,统一处理请求对象
_axios.interceptors.request.use(
  (config) => {
    // Do something before request is sent  在发送请求之前做一些事情
    console.log("在发送请求之前做一些事情",_axios.defaults.headers.common['Authorization'])
    // 统一请求头处理
    //请求的 config 参数设置的优先级更高,请求的 config 参数设置了Authorization取config 参数的Authorization,否则取初始化默认的Authorization
    const token = !!config.headers.Authorization?config.headers.Authorization:_axios.defaults.headers.common['Authorization'];
    token && (config.headers.Authorization = token);
    return config;
  },
  (error) => {
    // Do something with request error  处理请求错误
    return Promise.reject(error);
  }
);

// Add a response interceptor  添加响应拦截器
_axios.interceptors.response.use(
  (response) => {
    // Do something with response data  使用响应数据执行某些操作
    return response;
  },
  (error) => {
    // Do something with response error  处理响应错误
    if (error.response && error.response.status) {
      switch (error.response.status) {
        // 401: 未登录
        // 未登录则跳转登录页面,并携带当前页面的路径
        // 在登录成功后返回当前页面,这一步需要在登录页操作。
        case 401:
          console.info("跳转登录页");
          break;
        // 403 token过期
        // 登录过期对用户进行提示
        // 清除本地token和清空vuex中token对象
        // 跳转登录页面
        case 403:
          console.info("跳转登录页登陆过期");
          // 清除token
          // localStorage.removeItem("token");
          // store.commit('loginSuccess', null);
          // 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
          setTimeout(() => {
            console.info("跳转过期");
          }, 1000);
          break;
        // 404请求不存在
        case 404:
          console.info("404");
          break;
        // 其他错误,直接抛出错误提示
        default:
          console.info("其他错误");
      }
      return Promise.reject(error.response);
    } else {
      return Promise.reject(error);
    }

  }
);
/************************************************************************************************/
Plugin.install = (Vue, options) => {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;

Notice:

axios.defaults.headers.common['Authorization'] = `Bearer ${"inittoken"}`

or

  headers: {

              "Content-Type": "application/json;",

              Authorization: `Bearer ${"customtoken"}`,

            },

Question: Why do we need to add the word Bearer and a space in front of the token?

Answer: It is a norm to add the word Bearer and a space in front of the token. The space in front of the token is essential.

Authorization: `Bearer ${"customtoken"}`。

 

 3. Introducing Axios

Introduce axios into the main.js entry file, as shown below:

import './plugins/axios'

 All main.js codes:

import Vue from 'vue'
import './assets/iconfont/iconfont.css'
import './assets/fonts/DS-DIGI.css'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
import './plugins/axios'
// import axios from "axios";
// Vue.prototype.$axios = axios;
import configMethods from './config/config.js'
configMethods.GetConfig() //url接口初始化调用
    import './mockserver/mockserver'  //js控制gif播放暂停插件不能与mockjs插件一起用
    /**
     ***
    gif必须与正在加载的页面位于同一域( 以及端口和协议)。 该库通过解析js中的gif图像数据、 提取单个帧并在画布元素上渲染它们来工作。 无法从普通图像加载中获取原始图像数据, 因此此库对图像执行XHR请求, 并强制MIME类型为“ text / plain”。 因此, 使用此库受到与任何其他XHR请求相同的跨域限制。
     **/
import { setTheme, themeList } from '@/themeConfig/setTheme.js' ///样式主题
if (!!window.localStorage.getItem('themeProperty')) {
    setTheme(window.localStorage.getItem('themeProperty'))
} else {
    setTheme("")
}

Vue.config.productionTip = false

4. Use Axios

Usage example:

this.$axios.post(url,req(input parameter),config(axios config configuration)

.then(res=>{})

.catch(error=>{})

Note: The config parameter setting of Axios request has a higher priority than the interceptor.

 GetData() {
      this.$axios
        .post(
          AxiosUrl.HomePageUrlPath + "GetPredictData",
          JSON.stringify({
            Name: 13,
            Age: 13,
          }),
          {
            // 这里是 axios 的 config
            headers: {
              "Content-Type": "application/json;",
              Authorization: `Bearer ${"customtoken"}`,
            },
            // onUploadProgress: (progressEvent) => {
            //   // `onUploadProgress` 允许为上传处理进度事件
            //   // 浏览器专属
            //   // 处理原生进度事件
            //   console.log("上传处理进度事件",progressEvent)
            // },
            // onDownloadProgress: (progressEvent) => {
            //   // `onDownloadProgress` 允许为下载处理进度事件
            //   // 浏览器专属
            //   // 处理原生进度事件
            //   console.log("下载处理进度事件",progressEvent)
            // },
            signal: this.abortController.signal,
          }
        )
        .then((res) => {
          console.log("res", res);
        });
    },

5. Token settings

1. Unified settings in the interceptor

const _axios = axios.create(config);
//request 拦截器,统一处理请求对象
_axios.interceptors.request.use(
  (config) => {
    // Do something before request is sent  在发送请求之前做一些事情
    console.log("在发送请求之前做一些事情",_axios.defaults.headers.common['Authorization'])
    // 统一请求头处理
    //请求的 config 参数设置的优先级更高,大于拦截器,请求的 config 参数设置了Authorization取config 参数的Authorization,否则取初始化默认的Authorization
    const token = !!config.headers.Authorization?config.headers.Authorization:_axios.defaults.headers.common['Authorization'];
    token && (config.headers.Authorization = token);
    return config;
  },
  (error) => {
    // Do something with request error  处理请求错误
    return Promise.reject(error);
  }
);

2.Set when sending request 

  GetData() {
      this.$axios
        .post(
          AxiosUrl.HomePageUrlPath + "GetPredictData",
          JSON.stringify({
            Name: 13,
            Age: 13,
          }),
          {
            // 这里是 axios 的 config
            headers: {
              "Content-Type": "application/json;",
              Authorization: `Bearer ${"customtoken"}`,
            },
            // onUploadProgress: (progressEvent) => {
            //   // `onUploadProgress` 允许为上传处理进度事件
            //   // 浏览器专属
            //   // 处理原生进度事件
            //   console.log("上传处理进度事件",progressEvent)
            // },
            // onDownloadProgress: (progressEvent) => {
            //   // `onDownloadProgress` 允许为下载处理进度事件
            //   // 浏览器专属
            //   // 处理原生进度事件
            //   console.log("下载处理进度事件",progressEvent)
            // },
            signal: this.abortController.signal,
          }
        )
        .then((res) => {
          console.log("res", res);
        });
    },

 

 Note: The Authorization priority set when sending the request is higher!

6. Cancellation request 

AbortController, from  v0.22.0 the beginning, Axios supports the fetch API method -  AbortController  cancels requests:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// 取消请求
controller.abort()

Use in vue: 

  1. AbortControlller Create an instance in component data 

  2. config Add  signal : abortController.sinal this option to all requests that may need to be terminated 

  3. When leaving the page,  abortController.abort() just end all requests with

export default {
	// 在页面离开的时候,取消掉所有的这些请求即可,不管有没有完成
    beforeDestroy() {
        this.abortController.abort()
    },
    data(){
        return {
            abortController: new AbortController() // 用于取消请求
        }
    },
    methods: {
     GetData() {
      this.$axios
        .post(
          AxiosUrl.HomePageUrlPath + "GetPredictData",
          JSON.stringify({
            Name: 13,
            Age: 13,
          }),
          {
            // 这里是 axios 的 config
            headers: {
              "Content-Type": "application/json;",
              Authorization: `Bearer ${"customtoken"}`,
            },
            signal: this.abortController.signal,
          }
        )
        .then((res) => {
          console.log("res", res);
        });
    },
    }
}

7. Test cancellation request

Write a for loop test that calls the interface. as follows:

Reference links: 

1. Sample code for axios in vue to prevent multiple triggers from terminating multiple requests (anti-shake)_vue.js_Script Home

2.vue discards all unfinished requests when the page leaves. AbortController signal / CancelToken.cancel cancels the request_vue leaves the page event_October ooOO's blog-CSDN blog

3.Axios encapsulation is implemented in multiple ways and detailed explanation of advanced usage (file upload, request retry, request cancellation, etc.)_axios encapsulation detailed explanation_Lewenx's blog-CSDN blog 4. Abort one or more Web requests_Front-end essence  blog -CSDN Blog

5.https://www.cnblogs.com/Qooo/p/14054116.html

6. Cancel request | Axios Chinese documentation | Axios Chinese website 

Guess you like

Origin blog.csdn.net/qq_37312180/article/details/128971623