我试图在拦截器中发送不同的请求

我想在请求头中 for each 请求发送accessToken授权,除了一个 case

所以我在拦截器请求中编写了这段代码.使用

config.headers = {authorization: `Bearer ${accessToken}`};

但是如果这个错误发生了

error.response.data.code === 'expired'

我想发送refreshtoken,而不是accesstoken

所以我在拦截器中编写了这段代码.回答使用错误

const { data } = await axios.post(
  `${Config.API_URL}/user/refreshToken`,
  {},
  { headers: { authorization: `Bearer ${refreshToken}` } }
);

这是我的密码

useEffect(() => {
  axios.interceptors.request.use(async (config: any) => {
    const accessToken = await EncryptedStorage.getItem("accessToken");
    config.headers = { authorization: `Bearer ${accessToken}` };
    return config;
  });

  axios.interceptors.response.use(
    (response) => {
      return response;
    },
    async (error) => {
      const {
        config,
        response: { status },
      } = error;
      if (status === 419) {
        if (error.response.data.code === "expired") {
          const originalRequest = config;
          const refreshToken = await EncryptedStorage.getItem("refreshToken");
          const { data } = await axios.post(
            `${Config.API_URL}/user/refreshToken`,
            {},
            { headers: { authorization: `Bearer ${refreshToken}` } }
          );
          return axios(originalRequest);
        }
      }
      return Promise.reject(error);
    }
  );
}, [dispatch]);

我如何修复我的代码?

标题.仍在请求accesstoken授权.

推荐答案

使您的请求拦截器只设置一个默认的authorization头,而不覆盖已经存在的任何内容

axios.interceptors.request.use(async (config) => {
  const accessToken = await EncryptedStorage.getItem("accessToken");
  return {
    ...config,
    headers: {
      authorization: `Bearer ${accessToken}`,
      ...config.headers
    }
  }
});

您还可以避免完全提出getItem()个请求,这可能会节省一点时间

axios.interceptors.request.use(async (config) => {
  if (!config.headers.authorization) {
    config.headers.authorization = `Bearer ${await EncryptedStorage.getItem("accessToken")}`
  }
  return config;
});

Node.js相关问答推荐

使用OpenAI API时遇到问题

在我的Next.js应用程序中没有正确设置Process.env.NODE_ENV

Mongoose-不会更新数组中的属性值

对于具有重叠列的组合键,在冲突&q;上没有唯一或排除约束匹配错误

Puppeteer 在本地运行良好,但在 Heroku 中运行不佳

在nodejs中为oauth请求创建和存储csrf令牌的最佳方法

在 Nest 项目上运行 Jest 测试时,我的文件无法找到一个在测试之外没有任何问题的模块

如何设置 Puppeteer Select 器的唯一性?

在路由上使用中间件时,Nodejs Express 应用程序失败

如何找到特定文档并更新数组中特定键的值?

图像存储在后端文件夹中,但使用 multer 和 react.js 在前端找不到

多个 Axios 请求合并

aws cdk 2.0 init 应用程序无法构建更漂亮的问题,这来自 jest-snapshot

当我使用 uuid 代码意外崩溃,然后工作正常?

在 Express-js 中使用路由

Nodejs-console.error vs util.debug

如何在 node 调试器中禁用第一行中断

从 CoffeeScript 中的数组中删除一个值

使用 Socket.io 将客户端连接到服务器

使用 Node.js 和 Express 进行简单的 API 调用