I am learning JWT for a project that I must submit. I tested something using the VS Code plugin REST Client and it worked, but when I try the same using Postman (in the project they ask me to use Postman) it doesn't work.
My code is the following:
require("dotenv").config();
const express = require("express");
const app = express();
const jwt = require("jsonwebtoken");
const posts = [
{
username: "John",
title: "Post 1",
},
{
username: "Joe",
title: "Post 2",
},
];
app.use(express.json());
app.get("/posts", authToken, (req, res) => {
res.json(posts.filter((post) => post.username === req.user.name));
});
app.post("/login", (req, res) => {
const username = req.body.username;
const user = { name: username };
const tokenAccess = jwt.sign(user, process.env.TOKEN);
res.json({ tokenAccess: tokenAccess });
});
app.listen(4000);
function authToken(req, res, next) {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.TOKEN, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
In the .env file, I wrote:
TOKEN='71e30f718719170cf4a727a9'
TOKEN_REFRESH='b5010378bf2bd96c3000e48e'
Using the REST Client plugin, I created a test.rest file:
GET http://localhost:4000/postsAuthorization: Bearer XXXX
###
POST http://localhost:4000/login
Content-Type: application/json
{"username": "John"}
To try it, I send the POST request and I receive the token, which I put instead the XXXX space. Then I send the GET request and it works.
But as I said, when I try the same on Postman, it doesn't work. I do receive the token when I send the POST request, but when I use it to send the GET request, I receive an empty array. Could you please give me the instructions to do it well? Thanks a lot!
question from:
https://stackoverflow.com/questions/65928632/jwt-test-works-on-rest-client-but-it-doesnt-work-on-postman 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…