I dont know if this has been asked before, but i feel like ive scoured the internet and found close to nothing on the topic.
Im quite new to node and JWT but what i want to do is to generate a JWT and then store it in the Authorization header so that i can access it from the backend and send it to the frontend. It should look something like "Authorization: Bearer TOKEN".
Im also using passport and passport-jwt to authorise the user, so when doing something like
res.setHeader('authorization', 'Bearer ' + token');
I get this error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. Because passport has already redirected the response maybe?
When i searched for an answer it seemed like most people just used postman or rest as an example and assumed that we would find how to add the token to the headers ourselves. Im guessing its straightforward, but what am i missing?
Here is my code
postLogin = async (req, res, next) => {
await passport.authenticate('local', { //Authenticate user
successRedirect: '/',
failureRedirect: '/users/login',
failureFlash: 'Username or Password incorrect'
})(req, res, next);
const user = await User.findOne({ email: req.body.email });
const token = await auth.generateAccessToken(user.toObject());
res.setHeader('Authorization', 'Bearer ' + token); //Save accesstoken to authorization header
console.log(headers);
}
and
const generateAccessToken = async (user) => {
return new Promise((resolve, reject) => {
jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '30s'
},
(err, token) => {
if (err)
reject(err);
else {
console.log(`Someone generated token: ${token}`);
resolve(token);
}
});
});
}
Thanks in advance :D