Search code examples
reactjsaxioslocal-storageinterceptorbearer-token

Even though I send bearer token inside the Axios , it returns as unauthorized


In my react app I am using axios to perform the REST api requests.

However, when I send the Authorization header with the request, it returns 401 code, what should I do?

Here is my code:

import Axios from "axios";
import { BASE_URL } from "@configs";

export const axios = Axios.create({
  baseURL: BASE_URL,
  // https://xyz.abc.com
});

axios.interceptors.request.use((config) => {
  const token = localStorage.getItem("accessToken");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
    config.headers["Content-Type"] = "application/json";
  }
  return config;
});

My App.js:

import React, { Suspense, useEffect } from "react";

// ** Router Import
import Router from "./router/Router";
import { axios } from "@lib/axios";

const App = () => {
  const getAllData = async () => {
    try {
      const res = await axios(`/data`);
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getAllData();
  }, []);

  return (
    <Suspense fallback={null}>
      <Router />
    </Suspense>
  );
};

export default App;

vite.config.js:

import fs from "fs";
import * as path from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import rollupNodePolyFill from "rollup-plugin-node-polyfills";
import NodeGlobalsPolyfillPlugin from "@esbuild-plugins/node-globals-polyfill";

export default () => {
  return defineConfig({
    plugins: [react()],
    define: {
      global: "globalThis",
    },
    server: {
      port: 3000,
      proxy: "https://pixinvent.com/",
      cors: {
        origin: ["https://pixinvent.com/", "http://localhost:3000"],
        methods: ["GET", "PATCH", "PUT", "POST", "DELETE", "OPTIONS"],
        allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          includePaths: ["node_modules", "./src/assets"],
        },
      },
      postcss: {
        plugins: [require("postcss-rtl")()],
      },
    },
    resolve: {
      alias: [
        {
          find: /^~.+/,
          replacement: (val) => {
            return val.replace(/^~/, "");
          },
        },
        { find: "stream", replacement: "stream-browserify" },
        { find: "crypto", replacement: "crypto-browserify" },
        { find: "@src", replacement: path.resolve(__dirname, "src") },
        { find: "@store", replacement: path.resolve(__dirname, "src/redux") },
        {
          find: "@configs",
          replacement: path.resolve(__dirname, "src/configs"),
        },
        {
          find: "url",
          replacement: "rollup-plugin-node-polyfills/polyfills/url",
        },
        {
          find: "@styles",
          replacement: path.resolve(__dirname, "src/@core/scss"),
        },
        {
          find: "util",
          replacement: "rollup-plugin-node-polyfills/polyfills/util",
        },
        {
          find: "zlib",
          replacement: "rollup-plugin-node-polyfills/polyfills/zlib",
        },
        {
          find: "@utils",
          replacement: path.resolve(__dirname, "src/utility/Utils"),
        },
        {
          find: "@hooks",
          replacement: path.resolve(__dirname, "src/utility/hooks"),
        },
        {
          find: "@assets",
          replacement: path.resolve(__dirname, "src/@core/assets"),
        },
        {
          find: "@layouts",
          replacement: path.resolve(__dirname, "src/@core/layouts"),
        },
        {
          find: "@lib",
          replacement: path.resolve(__dirname, "src/lib"),
        },
        {
          find: "assert",
          replacement: "rollup-plugin-node-polyfills/polyfills/assert",
        },
        {
          find: "buffer",
          replacement: "rollup-plugin-node-polyfills/polyfills/buffer-es6",
        },
        {
          find: "process",
          replacement: "rollup-plugin-node-polyfills/polyfills/process-es6",
        },
        {
          find: "@components",
          replacement: path.resolve(__dirname, "src/@core/components"),
        },
      ],
    },
    esbuild: {
      loader: "jsx",
      include: /.\/src\/.*\.js?$/,
      exclude: [],
      jsx: "automatic",
    },
    optimizeDeps: {
      esbuildOptions: {
        loader: {
          ".js": "jsx",
        },
        plugins: [
          NodeGlobalsPolyfillPlugin({
            buffer: true,
            process: true,
          }),
          {
            name: "load-js-files-as-jsx",
            setup(build) {
              build.onLoad({ filter: /src\\.*\.js$/ }, async (args) => ({
                loader: "jsx",
                contents: await fs.readFileSync(args.path, "utf8"),
              }));
            },
          },
        ],
      },
    },
    build: {
      rollupOptions: {
        plugins: [rollupNodePolyFill()],
      },
    },
  });
};

Maybe the issue come from here? I tried with the normal axios headers method, but I got the 401 code again, maybe I need to recognize it here. When I try it in Postman, I can get the data.


Solution

  • import Axios from "axios";
    import { BASE_URL } from "@configs";
    
    export const axios = Axios.create({
      baseURL: BASE_URL,
      // https://xyz.abc.com
    });
    
    axios.interceptors.request.use((config) => {
      const token = JSON.parse(localStorage.getItem("accessToken"));
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
        config.headers["Content-Type"] = "application/json";
      }
      return config;
    });
    

    The issue was mine because I used the data without parsing, I overlooked it, when I did it like this, it was fixed.