【发布时间】:2020-07-18 09:34:50
【问题描述】:
我想创建一个带有拦截器的全局 axios 实例,该拦截器添加带有访问令牌的标头。 访问令牌存储在 cookie 中,但我不知道如何访问拦截器内部的 cookie,因为它不是反应组件。
我曾尝试在这样的自定义挂钩中创建 axios 实例:
import React, { useEffect, useState } from "react";
import { useCookies } from "react-cookie";
import axios from "axios";
function useApiClient() {
const [cookies, setCookie] = useCookies(["token"]);
const [client, setClient] = useState(null);
useEffect(() => {
setClient(
axios
.create({
baseURL: "http://localhost:8080/api/",
responseType: "json",
})
.interceptors.request.use(
(config) => {
console.log("setting up");
if (cookies["token"] != null) {
config.headers.authorization = cookies["token"];
}
},
(error) => Promise.reject(error)
)
);
}, [client]);
return client;
}
export default useApiClient;
但是当我尝试使用以下方法调用它时:
const client = useApiClient();
function attemptLogin() {
const credentials = {
username: username,
password: password,
};
client
.post("/authenticate", JSON.stringify(credentials), {
headers: {
"Content-Type": "application/json",
},
}).then(....)
我得到以下错误:
TypeError: client.post 不是函数
谁能帮忙?
【问题讨论】:
-
我注意到的一个问题是您需要在数组中像这样的客户端依赖项:
[client]在 useEffect 中。您还可以展示如何使用 client.post 吗? -
嗨@SuleymanSah 比你的评论。我曾尝试在数组中添加依赖项,但没有运气。我已经编辑了我的问题以显示我如何使用客户端。
-
您是否考虑过 axios 配置的
withCredentials: true选项?