Samra
Samra

Reputation: 2015

Correct way to use axios interceptors

I want to add jwt token to my axiosinstance in Login.js but it is giving me error

IDX12729: Unable to decode the header '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' as Base64Url encoded ...]

Here is my code:

Login.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);
  })
}

Upvotes: 1

Views: 11354

Answers (2)

Phil
Phil

Reputation: 164766

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. Wherever you created your axiosInstance is a good candidate.

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.

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

Upvotes: 1

Ricky Mo
Ricky Mo

Reputation: 7628

use doesn't return a config for you to pass into requests. 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);
  })

Upvotes: 2

Related Questions