How to configure token for Axios interceptor in Vue

Time:2021-1-23

After understanding the functions of cookie, session and token, learn how to use token

cookie

Cookie sends parameters to the background with the URL, which has the lowest security and limited size, no more than 4KB. Its data is stored in the client

session

The session data is stored in the server and a space is opened up in the memory to store the data. The session file name, that is, the session ID, is stored in the cookie. After the cookie is sent to the server, the session file is matched on the server

token

Token is an algorithm of the server. If the login is successful, the server will generate a string according to the algorithm and pass the string back to the client. This string is the token, which has the highest security

All of the above may be attacked by CSRF

Axios interceptor will process the request before sending it, put the token into the key and save it in the request header, which is agreed by the front and back office. After this configuration, every time a request is sent, the request header will carry the token and send it to the background for verification.

Features of Axios (official website)

  • Support browser and node.js
  • Promise support
  • It can intercept requests and responses
  • Can convert request and response data
  • Can I cancel the request
  • Automatic conversion of JSON data
  • Browser side support to prevent CSRF (Cross Site Request Forgery)

Method 1: when using Axios request, we can first obtain the token that we have stored in localstorage

Then use […] in the interceptor ]Splicing


import axios from 'axios';
import qs from 'qs';
axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
let token = localStorage.getItem('token')
// Add a request interceptor
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  //console.log(config)
  if(config.method==='post'){
    config.data=qs.stringify({
      token:token,
      ...config.data
    })
  }else if(config.method==='get'){
    config.params={
      token:token,
      ...config.params
    }
  }
  return config;
 }, function (error) {
  // Do something with request error
  return Promise.reject(error);
 });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
 }, function (error) {
  // Do something with response error
  return Promise.reject(error);
 });

 class http{
   static get(url,params){
     return axios.get(url,params)
   }
   static post(url,params){
    return axios.post(url,params)
  }
 }
 export default http;

Method 2

Axios modify global default configuration:


axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Axios configuration Interceptor:

//Add a request interceptor
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  return config;
  //It is often used with token. Configure the token value to the token key and put the token key in the request header
  config.headers['Authorization'] = token;
  
 }, function (error) {
  // Do something with request error
  return Promise.reject(error);
 });

//Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
 }, function (error) {
  // Do something with response error
  return Promise.reject(error);
 });

These two methods allow us to splice tokens in Axios interceptor instead of adding a token value to every request

summary

The above is Xiaobian’s introduction of how to configure the token for Axios interceptor in Vue. I hope it can help you. If you have any questions, please leave me a message and Xiaobian will reply you in time. Thank you very much for your support to developer!
If you think this article is helpful to you, please reprint, please indicate the source, thank you!