Recover token with json web token and nodejs

0

Good I have an api made with express but I do not know how to save the token, any help?

Controller code that creates the token which works correctly:

function login(req, res) {
    const {
        name,
        pass
    } = req.body
    let query = 'SELECT * FROM users WHERE name = ? AND password =?'
    mysqlConnection.query(query, [name, pass], (err, rows, fields) => {
        if (rows == 0) {
            res.status(401).send({
                error: 'usuario o contraseña inválidos'
            })
            return
        }
        if(err){
            console.log(err)
        }
        var tokenData = {
            username: name
        }

        var token = jwt.sign(tokenData, 'Secret Password', {
            expiresIn: 60 * 60 * 12
        })

        res.send({
            token
        })
    })
}

Code of the service that verifies the token which never arrives:

function token (req, res) {
  var token = req.headers['authorization']
  if (!token) {
    res.status(401).send({
      error: "Es necesario el token de autenticación"
    })
    return
  }

  token = token.replace('Bearer ', '')

  jwt.verify(token, 'Secret Password', function (err, user) {
    if (err) {
      res.status(401).send({
        error: 'Token inválido'
      })
    } else {
      res.send({
        message: 'Awwwww yeah!!!!'
      })
    }
  })
}
    
asked by Mario 21.11.2018 в 19:10
source

0 answers