即使我在Axios内部发送不记名令牌,它也会返回为未经授权

exdqitrt  于 2023-08-04  发布在  iOS
关注(0)|答案(1)|浏览(137)

在我的react应用程序中,我使用axios来执行REST API请求。
但是,当我发送Authorization头和请求时,它返回401代码,我该怎么办?
下面是我的代码:

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()],
      },
    },
  });
};


问题可能来自这里。我尝试了正常的axios头方法,但我再次得到了401代码,也许我需要在这里识别它。当我在Postman中尝试它时,我可以获得数据。

k3fezbri

k3fezbri1#

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

字符串
这个问题是我的,因为我使用的数据没有解析,我忽略了它,当我这样做,它是固定的。

相关问题