'React axios Interceptors: Authorization invalid token

Axios interceptors works really well for http://127.0.0.1:8000 local API calls. Here is the working code.

import axios from 'axios';

const http = axios.create({
  baseURL: 'http://127.0.0.1:8000/api/',
  Headers: {},
});

try {
  http.interceptors.request.use(
    (config) => {
      let data = JSON.parse(localStorage.getItem('cyber-minds'));

      if (data && data.user_status.token) {
        config.headers['Authorization'] = 'Token ' + data.user_status.token;
      }

      return config;
    },

    (error) => {
      return Promise.reject(error);
    }
  );
} catch (error) {
  console.log(error);
}

export default http;

But after I deploy http://127.0.0.1:8000 to https://mysite-backend.herokuapp.com and replace my baseURL with https://mysite-backend.herokuapp.com it returns invalid token. here is the code which returns invalid token.

import axios from 'axios';

const http = axios.create({
  baseURL: 'https://cyberminds-backend.herokuapp.com/api/',
  Headers: {},
});

try {
  http.interceptors.request.use(
    (config) => {
      let data = JSON.parse(localStorage.getItem('cyber-minds'));

      if (data && data.user_status.token) {
        config.headers['Authorization'] = 'Token ' + data.user_status.token;
      }

      return config;
    },

    (error) => {
      return Promise.reject(error);
    }
  );
} catch (error) {
  console.log(error);
}

export default http;

Here is local storage information.

{token: "e3746603ad6c8788b9936118f1fc36289bb20a8d", user: {id: 2,…},…}
assetRisk: "Low"
cid: 1
cpe: "cpe:2.3:a:oracle:peoplesoft_enterprise:8.22.14"
id: 2
name: ""
pid: 2
pr: "Windows"
token: "e3746603ad6c8788b9936118f1fc36289bb20a8d"
user: {id: 2,…}
user_status: {loggedIn: true, token: "e3746603ad6c8788b9936118f1fc36289bb20a8d"}
vendor: "Oracle"

The authentication is working very well. Authorization returns invalid token how can i resolve this issue?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source