gpt4 book ai didi

javascript - 在 Axios 创建函数中添加额外的 header

转载 作者:行者123 更新时间:2023-12-05 03:18:04 24 4
gpt4 key购买 nike

我已经实现了从 Axios 发送请求的功能,

export const http = axios.create({
baseURL: 'https://someurl/api',
headers: {
'Content-type': 'application/json',
Accept: 'application/json',
},
});

所以我可以在我的应用程序的任何地方调用这个方法,

   import {http} from 'src/helpers/HttpHelper';

http
.post(
'/users',
{name: 'mishen'},
)
.then(res => console.log(res))
.catch(error => console.log());

由于也有需要承载 token 的 protected 路由,因此我尝试在我的组件中执行类似的操作,

import {useContext} from 'react';
import {http} from 'src/helpers/HttpHelper';

const MyComponent = () => {
const {userToken} = useContext(AuthContext);
const signUpUser = () => {
http
.post(
'/app_user_role_selection',
{name: 'mishen'},
{headers: {Authorization: `Bearer ${userToken}`}}
)
.then(res => console.log(res))
.catch(error => console.log());
}
...
}

但是,这不起作用。

最佳答案

您可以使用 axios interceptors .

export const http = axios.create({
baseURL: "url",
headers: {
"Content-type": "application/json",
Accept: "application/json"
}
});

http.interceptors.request.use(async (config) => {
const value = await AsyncStorage.getItem("your key");
if (value !== null) {
config.headers["Authorization"] = `Bearer ${value}`;
}

return config;
});


const MyComponent = () => {
const signUpUser = () => {
http
.post(
"/app_user_role_selection",
{ name: "mishen" }
)
.then((res) => console.log(res))
.catch((error) => console.log());
};
};

关于javascript - 在 Axios 创建函数中添加额外的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73861906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com