【发布时间】: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
如何避免?
【问题讨论】:
-
钩子只能在功能性反应组件内部调用。 Only Call Hooks at the Top Level
-
好的,你能展示代码示例如何解决我的问题吗?
标签: reactjs typescript axios