Reputation: 39
I writing code for authorization. After click on the button for login I create a new header with
res.header('Authorization', token)
admin_login router:
router.post('/admin_login', async (req, res) => {
const adminDB = data.admins;
const admin = adminDB.find(admin => req.body.email === admin.email)
if (!admin) return res.status(400).send('Email in not found!')
if (admin.password !== req.body.password) return res.status(400).send('Invalid password')
const token = jwt.sign({ admin }, 'the_secret_key')
res.header('Authorization', token)
res.redirect('/admin')
})
I wont to recieve Authorization header after login in admin router, but I wont recieve it. I see Authorization header in
Code for verification:
const jwt = require('jsonwebtoken')
module.exports = (req, res, next) => {
const token = req.header('Authorization')
console.log(token)
if (!token) return res.status(401).send('Access Denied')
try {
const verified = jwt.verify(token, 'the_secret_key')
req.admin = verified
next()
} catch (e) {
res.status(400).send('Invalid token')
}
}
first img: headers in admin router
second img: headers in admin_login router after click on the button for login
Please, help me
Upvotes: 0
Views: 15909
Reputation: 1074028
As far as I can tell from the documentation, there is no header
method on the Express Request
object or the Node.js IncomingMessage
it extends.
The Express documentation says that to retrieve a header, you use get
:
req.get(field)
Returns the specified HTTP request header field (case-insensitive match).
So:
const token = req.get("Authorization");
Or you could use the headers
object from IncomingMessage
:
const token = req.headers["authorization"];
(Note the lower case, Node.js makes the header names lower case when building the object.)
Upvotes: 11