尝试在 Node.js 和 React 中获取 jwt 键时出现语法错误

Posted

技术标签:

【中文标题】尝试在 Node.js 和 React 中获取 jwt 键时出现语法错误【英文标题】:Syntax error when trying to fetch jwt key in Node.js and React 【发布时间】:2021-08-15 23:28:34 【问题描述】:

我一直在尝试从我实现的 REST API 中获取 jwt 令牌,但是每次我尝试按照我在网上找到的教程进行操作时都会出错。我一直在寻找这个问题 4 个小时,但我无法找到解决方案。我阅读了所有其他问题和教程,例如:How do I store JWT and send them with every request using react。可悲的是,在我的情况下,每一个发现的犯规都不起作用。如果您至少能告诉我在哪里可以学习,我将不胜感激。我一直在使用我用 Node.js Express 创建的 REST API,其中有生成 JWT 的方法:

userSchema.methods.generateAuthenticationToken = function () 
  const token = jwt.sign(
     _id: this._id, admin: this.admin, premium: this.premium ,
    config.get(`jwtPrivateKey`)
  );
  return token;
;

我尝试像这样在 React 中获取数据:

await fetch("http://localhost:1234/api/auth", 
      method: "POST",
      body: JSON.stringify(item),
      headers: 
        "Content-Type": "application/json",
        Accept: "application/json",
      ,
    )
      .then(function (response) 
        return response.json();
      )
      .then(function (data) 
        localStorage.setItem("user-info", data.token);
      );

这是我收到的错误:

   Uncaught (in promise) SyntaxError: Unexpected token e in JSON at position 0

这是生成的 JWT 密钥:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MGE2YTg4YzQzZDU2MzIwMjg1NWZlZjIiLCJhZG1pbiI6dHJ1ZSwicHJlbWl1bSI6dHJ1ZSwiaWF0IjoxNjIyMTMzMzAwfQ.CmQRtSaZc8g3TEF6R7flpJ9499QnfzlfgPNVazFaUsY

【问题讨论】:

你确定它会返回 JSON 吗?看起来不像。 确切的反应是什么?似乎错误是因为您试图将其解析为 JSON,但它不是 JSON 格式。 这是我使用 console.log 得到的:响应 type: "cors", url: "localhost:1234/api/auth", redirected: false, status: 200, ok: true, ...跨度> 【参考方案1】:

尝试从您的 express 端点返回一个对象而不是字符串,例如:

  const token = jwt.sign(
     _id: this._id, admin: this.admin, premium: this.premium ,
    config.get(`jwtPrivateKey`)
  );
  return  token ;
;

【讨论】:

以上是关于尝试在 Node.js 和 React 中获取 jwt 键时出现语法错误的主要内容,如果未能解决你的问题,请参考以下文章

如何在 expo 中禁用 https-only fetch 请求 react native/node js

React-Router vs Node.js

MySQL 结果来自 html 中的 node.js,由 react.js

如何使用 mongoose 从 mongoDB 中获取一定数量的对象? (Node.js)

无法在 Node.JS 和 React-Native (Socket.IO) 之间建立连接

如何以 Node JS 作为后端将 Mysql 数据获取并显示到 ReactJS 前端?