【问题标题】:Add cookie to axios interceptor request handler将 cookie 添加到 axios 拦截器请求处理程序
【发布时间】:2021-08-04 15:33:18
【问题描述】:

我正在将 Axios 配置为始终使用标头 Authorization 发出请求,该请求的值位于用户 cookie 中。 我的代码:

import axios, { AxiosRequestConfig, AxiosResponse} from 'axios';
import {useCookies} from "react-cookie";
const [cookies] = useCookies(["myToken"]);

const customAxios = axios.create({
    baseURL: 'http://localhost/storeApi/',
    timeout: 10000,
});

const requestHandler = (request: AxiosRequestConfig) => {
    request.headers.Authorization = `Bearer ${cookies.jwtToken}`;
    return request;
};

customAxios.interceptors.request.use(
    (request) => requestHandler(request)
);

export default customAxios;

但我有一个错误:

 Line 3:19:  React Hook "useCookies" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function 

如何避免?

【问题讨论】:

标签: reactjs typescript axios


【解决方案1】:

因为它是一个 React Hook,你不能在 React 组件函数之外使用 useCookies:要访问一个 cookie,你需要从 document.cookie 读取它,或者安装另一个包,比如 cookie .

如果您只使用一个 cookie,则可以使用 w3School's cookie example(我已将其转换为 npm package)来摆脱困境:

function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i <ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

那就这样吧:

const cookie: string = getCookie('myToken');

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 1970-01-01
    • 2019-09-19
    • 2020-09-25
    • 1970-01-01
    • 2021-02-09
    • 2015-11-18
    • 1970-01-01
    • 2022-11-14
    相关资源
    最近更新 更多