将cookie添加到axios拦截器请求处理程序中



我将Axios配置为始终使用用户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 

如何避免这种情况?

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

如果你只使用一个cookie,你可以使用w3School的cookie示例(我已经把它变成了一个npm包):

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

相关内容

  • 没有找到相关文章

最新更新