Store the Token in the request header and send the interface request

Article Directory

1. Demand

After the user logs in, the token is stored in the request header of the next interface access to make an interface request

2. Analysis

import router from './router';
import {
    
     Message } from 'element-ui';
import Axios from 'axios'

router.beforeEach((to, from, next) => {
    
    
    if (to.path === '/login') {
    
    
      next();
    } else {
    
    
      let token = localStorage.getItem('Token');
      if (token === null || token === '') {
    
    
        Message.warning('请登录')
        next('/login');
      } else {
    
    
          next();
      }
    }
  });
// 添加请求拦截器,在请求头中加token
Axios.interceptors.request.use(
    config => {
    
    
      if (localStorage.getItem('TOKEN')) {
    
    
        config.headers.TOKEN = localStorage.getItem('TOKEN');
      }
      return config;
    },
    error => {
    
    
      return Promise.reject(error);
    });

Guess you like

Origin blog.csdn.net/qq_53810245/article/details/132607329