简体   繁体   中英

req.headers['authorization'] is undefined in Nodejs JWT(JSON WEB TOKEN)

Here is the code for JWT:

 const express = require("express"); const jwt = require("jsonwebtoken"); const app = express(); app.use(express.json()); const user = [ { name: "Rohan", id: 1, }, { name: "Sophie", id: 2, }, { name: "Charlie", id: 3, }, ]; app.get("/", (req, res) => { res.send("Welcome to Homepage"); }); app.get("/id", verifyToken, (req, res) => { res.json(user.filter((id) => user.name === req.user.name)); }); function verifyToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(" ")[1]; if (token == null) return res.sendStatus(401); jwt.verify(token, "secretKey", (err, user) => { if (err) return res.sendStatus(403); req.user = user; next(); }); } app.post("/login", (req, res) => { const username = req.body.username; const user = { name: username }; jwt.sign(user, "secretKey", (err, token) => { res.json({ token: token }); }); }); app.listen(4000, () => { console.log("Server is listening on port: 4000"); });

The req.headers['authorization'] is returning undefined when console.log(The req.headers['authorization'])

This code for JWT always return Status 401 (Unauthorized) when the request is sent in the format Authorization: Bearer "token",

Please help !!

Do you use the Postman for test?

add 'authorization' key in headers section on the postman, like picture:

在此处输入图像描述

and not need 'authHeader.split(" ") 1 ;', please change your code like this:

const token = req.headers["authorization"];
//   const token = authHeader && authHeader.split(" ")[1];
console.log(token)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM