当前位置:   article > 正文

axios请求头添加token_axios添加token

axios添加token
import axios from 'axios';
// http request 拦截器
const httpService = axios.create({
    baseURL: "", // 需自定义 // url前缀-'http:xxx.xxx'
    timeout: 900000, // 需自定义 请求超时时间   十五分钟
    withCredentials: false, // `withCredentials` 表示跨域请求时是否需要使用凭证
});

// request拦截器
httpService.interceptors.request.use(

    config => {
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
       let user = localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")):null
        if (user) {
            config.headers['token'] = user.token // 让每个请求携带自定义token 请根据实际情况自行修改
          }
        return config;
    },
    error => {
        // 请求错误处理
        return Promise.reject(error);
    }
)

httpService.interceptors.response.use(
    response => {
      if (response.data.errno === 999) {
        router.replace('/');
        console.log("token过期");
      }
      return response;
    },
    error => {
      return Promise.reject(error);
    }
  );
export default httpService;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

main.js

import axios from './axios/http.js'

// axios.interceptors.request.use( config => {
//   // console.log("config:", config);
//   config.headers.Authorization = window.sessionStorage.getItem("Token");
//   return config;
// });
Vue.prototype.axios = axios
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/886553
推荐阅读
相关标签
  

闽ICP备14008679号