0

I am new to node.js. I need to use Json Web Tokens to authenticate my login requests.

In Postman and in the devtools, POST requests are working well : a new jwt is created for each request (seePOSTMAN, see DEVTOOLS

But, my authorization headers does not contain any jwt... I got something like "Authorization : Bearer " (see AUTHORIZATION).

Here is my code :

**user.js/controllers **

exports.login = (req, res, next) => { 
  User.findOne({ email: req.body.email }) 
  .then(user => {
    if(!user) { 
      return res.status(401).json({ message: 'Utilisateur non trouvé !'}); 
      } 
      bcrypt.compare(req.body.password, user.password) 
      .then(valid => {
        if(!valid) {  
          return res.status(401).json({ message: 'Mot de passe incorrect !'}); 
         } 
          res.status(200).json({ 
            userId: user._id,
            token: jwt.sign(
              { userId: user._id}, 
              'RANDOM_TOKEN_SECRET', 
              { expiresIn: '24h' } 
            )
          });
        })
      .catch(error => res.status(500).json({ error }));
  })
  .catch(error =>  res.status(500).json({ error }));
};

**app.js **

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*'); 
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization'); 
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
  next();
});

How can I fix that ?

I'm running out of leads or solutions...

Thanks !

I am expecting to see the jwt appears just next to "Authorization: Bearer".

  • Does this answer your question? [How to add Bearer token to requestify post method in nodejs?](https://stackoverflow.com/questions/54018700/how-to-add-bearer-token-to-requestify-post-method-in-nodejs) – Justinas Nov 23 '22 at 09:01

0 Answers0