简体   繁体   English

axios拦截器的正确使用方法

[英]Correct way to use axios interceptors

I want to add jwt token to my axiosinstance in Login.js but it is giving me error我想在 Login.js 中将 jwt 令牌添加到我的 axiosinstance 中,但它给了我错误

IDX12729: Unable to decode the header '[PII is hidden. IDX12729:无法解码 header '[PII 被隐藏。 For more details, see https://aka.ms/IdentityModel/PII.]' as Base64Url encoded...]有关更多详细信息,请参阅 https://aka.ms/IdentityModel/PII。]' 作为 Base64Url 编码...]

Here is my code:这是我的代码:

Login.js登录.js

const printValues = e =>{

      axiosInstance.post('/auth', data)
.then(res =>{

  console.log("adding token");
  
  const config = axiosInstance.interceptors.request.use(function (config) {
    
    config.headers.Authorization =  res.data.token;

    return config;
  });

  axiosInstance.get('/User/GetUserByID/0', config)
  .then(res =>{
    //set user details
  })
  .catch(err =>{
    console.log(err);
  })
}

use doesn't return a config for you to pass into requests. use不会返回配置以供您传递给请求。 As long as you are using the same instance, the config would get altered.只要您使用相同的实例,配置就会被更改。

  axiosInstance.interceptors.request.use(function (config) {
    
    config.headers.Authorization =  res.data.token;

    return config;
  });

  axiosInstance.get('/User/GetUserByID/0')
  .then(res =>{
    //set user details
  })
  .catch(err =>{
    console.log(err);
  })

First, don't define interceptors within a response handler.首先,不要在响应处理程序中定义拦截器。 That means you'll be adding an interceptor every time you make that request.这意味着您每次发出请求时都会添加一个拦截器。

Typically you would keep your token state and interceptor separate from other application code.通常,您会将令牌 state 和拦截器与其他应用程序代码分开。 Wherever you created your axiosInstance is a good candidate.无论您在哪里创建axiosInstance都是不错的选择。

For example...例如...

import axios from "axios"

const axiosInstance = axios.create({
  // ..
})

const token = null // initial state

axiosInstance.interceptors.request.use(async config => {
  if (!token) {
    // note, use a separate axios instance for this request
    const { data } = await axios.post("/auth", dataFromSomewhere)
    token = data.token
  }

  config.headers.Authorization = `Bearer ${token}` // you may need "Bearer" here
  return config
})

Now you can use axiosInstance to make requests and it will transparently resolve your authorisation token if required before continuing.现在您可以使用axiosInstance发出请求,如果需要,它将透明地解析您的授权令牌,然后再继续。

const printValues = e => {
  axiosInstance.get("/User/GetUserByID/0")
  .then(res =>{
    //set user details
  })
  .catch(err =>{
    console.log(err);
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM