首页 > 解决方案 > 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.jsreactjsrestpostmanbearer-token

解决方案


推荐阅读