node.js - ReactJS:使用 Bearer 授权获取 GET 方法
问题描述
我有带有路由的 Express API。现在我将客户端连接到服务器。
在 React 中,我完成了登录请求(接收 Bearer 令牌)。现在我正在尝试发出 GET Authorized 请求,我从服务器得到 401 Unauthorized 。从邮递员那里一切都好。我在谷歌浏览器中有 CORS 扩展。
服务器路由:
router.get('/tasks', auth, async (req, res) => {
try {
await req.user.populate('tasks').execPopulate()
res.send(req.user.tasks)
} catch (e) {
res.status(500).send()
}
登录请求没问题。
handleLogInClick = (email, password) => {
console.log("Trying to login ");
fetch("http://localhost:3000/users/login", {
// mode: "no-cors",
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify({ email: email, password: password }),
})
.then((res) => res.json())
.then((data) =>
this.setState({
data,
}),
);
this.getTasks("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9");
};
我知道令牌,所以我试图从服务器获取响应,将他传递给函数。我在标题中尝试了一些选项,但我失败了。方法 getTasks,下面有 401 错误
getTasks = (token) => {
token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZGNmZjFhMjQzZWUwNTJmNmNkMjAzYzgiLCJpYXQiOjE1NzM5ODEwODV9.qUY8RCpc6ABRX7qPw_ea8lKaFg9xDRw2fkiVne1L-s4";
fetch("http://localhost:3000/tasks", {
method: "GET",
mode: "no-cors",
headers: {
Accept: "application/json, text/plain, */*",
// "Content-Type": "application/json",
Authorization: "Bearer " + token,
},
})
.then((res) => res.json())
.then(
(tasks) =>
this.setState({
tasks,
}),
console.log(token),
);
};
来自邮递员的请求,带有选项:
GET /tasks HTTP/1.1 Host: localhost:3000 : , Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZGNmZjFhMjQzZWUwNTJmNmNkMjAzYzgiLCJpYXQiOjE1NzM5ODEwODV9.qUY8RCpc6ABRX7qPw_ea8lKaFg9xDRw2fkiVne1L-s4 User-Agent: PostmanRuntime/7.19.0 Accept: / Cache-Control: no-cache Postman-Token: b209d7ee-e254- 4594-9616-93ebc86bea99,8e867f14-1d0e-40b5-8f85-76a0d317af84 主机:localhost:3000 接受编码:gzip,放气连接:保持活动缓存控制:无缓存
在此先感谢您的帮助。
解决方案
推荐阅读
- node.js - 为什么有些数组似乎有键值对
- r - 如何随机化数据帧的几列中的值 - 以便共享时原始值或未知
- swift - 如何通过可观察的链视图控制器演示者
- python - 我必须使用“IN 运算符”但不能在代码中使用“True”来获得“True”作为答案
- javascript - Javascript逐渐改变饱和度
- javascript - 刷新令牌google api(日历)
- intellij-idea - 无法在 IntelliJ IDEA 2021.2 中执行 Maven 包装器验证目标
- python - KivyMD - ScreenManager 和 ids
- ios - Xcode 在 Xcode 12.5.1 的范围错误中找不到类型“WKWebView”
- mysql - 选择两个名称奇怪的列