reactjs - 将拦截器添加到 axios 的实例
问题描述
我正在尝试使用 React Native 在 axios 拦截器上更新我的应用程序令牌。我有这段代码可以连接到 API 后端:
const requestHelper = axios.create({
baseURL: "http://192.168.0.15:8000/api/",
headers: {
"Content-Type": "application/json",
Authorization: "token 3260b30bdbc19a5c4deed87327536e443c751d27",
},
});
const routes = {
accounts: {
getUser: () =>
requestHelper({
method: "get",
url: "accounts/detail/",
}),
.....
这是有效的,但令牌是硬编码的。现在,每次请求 API 调用时,我都需要从 AsyncStorage 更新该令牌。我试图使用 Axios 拦截器但不工作。这些是我的测试:
const requestHelper = axios.create({
baseURL: "http://192.168.0.15:8000/api/",
headers: {
"Content-Type": "application/json",
},
});
const createInterceptors = (instance) => {
instance.interceptors.request.use(
(config) => {
config.headers = {
Authorization: "token 3260b30bdbc19a5c4deed87327536e443c751d27",
};
return instance;
},
(error) => {
return Promise.reject(error);
}
);
return instance;
};
const routes = {
accounts: {
getUser: () =>
createInterceptors(
requestHelper({
method: "get",
url: "accounts/detail/",
})
),
....
令牌在这里也是硬编码的,但用于测试目的。此测试引发错误:
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'instance.interceptors.request')]
有谁知道如何实施?
解决方案
我解决了。我必须像这样添加拦截器功能:
const requestHelper = axios.create({
baseURL: "http://192.168.0.15:8000/api/",
headers: {
"Content-Type": "application/json",
},
});
requestHelper.interceptors.request.use(async (config) => {
const token = await AsyncStorage.getItem("token");
config.headers = {
Authorization: "token " + token,
};
return config;
});
推荐阅读
- c++ - CMake:在项目范围内传播编译选项
- parallel-processing - CUDA 中的块间同步
- json - 如何使用 MS Unit 模拟 WebAPI 的 PATCH 方法?
- javascript - webpack动态导入方法reactjs中返回的是空数组而不是文件,如何解决?
- php - $this 对象在加载的模板中,带有角度
- java - 错误 osweb.context.ContextLoader - 上下文初始化失败
- dependency-injection - .NET Core - 注册服务,如何注册服务的单独版本
- php - Laravel Maatwebsite 导出到 excel 不起作用
- r - 闪亮的模块:从外部访问和更改位于模块服务器功能内的反应值?
- compilation - 查找用于 macOS 的预编译或编译 Tcl/Tk 框架