0

Here is my verification function:

exports.validateToken = function(req, res, next){
  var token = req.body.token;
  jwt.verify(token, config.sessionSecret, function(err, decoded) {
     if(err){
         return next(err);
     }else{

        var userToken = jwt.sign(req.body.user, config.secret,{
            expiresIn:10000
        });

        res.json({token: userToken})

    }    
  });
}

I'm expecting an error definition but I'm getting an internal server error on top of that:

TokenExpiredError: jwt expired
at Object.JWT.verify (/Users/Developer/node_modules/jsonwebtoken/index.js:209:19)
at exports.validateToken (/Users/Developer/app/controllers/user.signing.controller.js:369:9)
at Layer.handle [as handle_request] (/Users/Developer/node_modules/express/lib/router/layer.js:76:5)
at next (/Users/Developer/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/Developer/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/Developer/node_modules/express/lib/router/layer.js:76:5)

What am I doing wrong here?

4

3 回答 3

1
const jwt = require('jsonwebtoken')

module.exports =  function auth (req,res,next) {
    const token =req.header('x-auth-token')
    if (!token){
        return res.status(401).send('to\'ken not found')
    }
 try{
        const decoded = jwt.decode(token,'m@hf1y')
         req.user = decoded
         next()

 }catch (e) {
     
     return  res.status(400).send('invalid token')
 }
}

编辑

警告:这是 usingjwt.decode而不是jwt.verify. 由于 JSON Web Token 总是可以在不知道密钥的情况下被解码,因此之前的代码只有在来自推力源时才有效。

于 2020-06-20T11:19:22.367 回答
-1

我已经在我的代码中尝试过了。res.locals.data有助于将数据传送到调用函数。

只需在调用函数中获取数据,res.locals.data您的问题就有望解决。

if (err) {
    res.locals.data = {
        err: err.name,
        message : err.message
    }
    return next();
}
于 2019-02-04T13:48:30.473 回答
-1

由于某种原因,下一个响应不起作用。所以我用下面的代码替换了它,一切都很好:

res.status(401).send({error:'invalid token'});
于 2016-02-26T04:46:53.040 回答