如何在拦截器中发送不同的请求?

How can I send different request in intercepter?

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

我想在请求中发送 accessToken header 除了一种情况之外的每个请求的授权

所以我在拦截器中写了这段代码request.use

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

但是如果发生这个错误

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

我想在 header 授权中发送 refreshtoken 而不是 accesstoken

所以我把这段代码写在interceptor.response.use.error

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

我该如何修复我的代码? 如果我使用我的代码 if error.response.data.code === 'expired'

仍在请求 headers.authorization 访问令牌。

让你的请求拦截器只设置一个默认值 authorization header 而不会覆盖任何已经存在的东西

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