gpt4 book ai didi

reactjs - Go Api 返回 Unauthorized

转载 作者:行者123 更新时间:2023-12-01 20:26:26 32 4
gpt4 key购买 nike

我是 GoLang+React 的新手。所以我开始了一个项目来学习。我用 GoLang 做了一个 RESTful Api。接口(interface) Link .我用那个api做了一个登录系统。并且成功地我可以登录并将用户数据设置为 sessionStorage。但问题是当我试图通过使用 axios 命中 api 的注销端点来注销用户时。第一次显示未经授权。第二次显示网络错误。

这是请求代码:

logout = () => {
const user = JSON.parse(sessionStorage.getItem('userData'));
const token = user.token;
const uid = user.id;
const url = "http://localhost:8000/logout"
axios.post(url,{"user_id":uid},{"Authorization":`Bearer ${token}`}).then((response) => response.json()).then((result) => {
let responseJson = result;
console.log(responseJson);
}).catch((error) => {
console.log(error);
})
}

注意:通过客户端应用程序我可以成功注销。但是通过 axios 我不能。

最佳答案

您需要提供身份验证 header headers 下Axios 的属性(property) config目的:

axios.post(
url,
{ user_id: uid },
{ headers: { 'Authorization': `Bearer ${token}` } }
)

解释:

这是axios post方法签名,查看 docs :
axios.post(url[, data[, config]])

第三个参数 config 应该有这个接口(interface):
{
...
baseURL?: string;
headers?: any; // this is for headers
params?: any;
....
}

关于reactjs - Go Api 返回 Unauthorized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61896973/

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