【发布时间】: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, ...}跨度>
标签: node.js reactjs express jwt