Reputation: 159
I have been trying to get jwt token from REST API I implemented, but every time I try to do it accordingly to tutorials I found online I get an error. I have been searching for this problem 4 hours now but I was unable to find a solution. I read all other questions and tutorials like: How do I store JWT and send them with every request using react. Sadly every found foulution didn't work in my case. I would be grateful if you could at least tell me where can I learn to do it. I have been using REST API I created with Node.js Express in which there is method to generate JWT:
userSchema.methods.generateAuthenticationToken = function () {
const token = jwt.sign(
{ _id: this._id, admin: this.admin, premium: this.premium },
config.get(`jwtPrivateKey`)
);
return token;
};
I try to fetch data in React like this:
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);
});
Here is error I receive:
Uncaught (in promise) SyntaxError: Unexpected token e in JSON at position 0
And here is JWT key that was generated:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MGE2YTg4YzQzZDU2MzIwMjg1NWZlZjIiLCJhZG1pbiI6dHJ1ZSwicHJlbWl1bSI6dHJ1ZSwiaWF0IjoxNjIyMTMzMzAwfQ.CmQRtSaZc8g3TEF6R7flpJ9499QnfzlfgPNVazFaUsY
Upvotes: 1
Views: 315
Reputation: 239
Try returning an object instead of a string from your express endpoint, for example:
const token = jwt.sign(
{ _id: this._id, admin: this.admin, premium: this.premium },
config.get(`jwtPrivateKey`)
);
return { token };
};
Upvotes: 3