我是 nodeJS 的新手,遇到了以下问题:我在我的一个 Controller 中定义了一个函数,我想用它来验证 JSON-Web-Token。我使用了以下功能:
exports.validate = function (token, cb) {
jwt.verify(token, secretToken, cb(err, decoded));
}
但是每次我想运行它时,nodeJS 都会给我一个错误,'err' is not defined?在 jwt-Example 中有以下示例:
// verify a token symmetric
jwt.verify(token, 'shhhhh', function(err, decoded) {
console.log(decoded.foo)
});
所以显然我在某处出错了,但我不知道是什么。我也不知道要寻找什么...我已经进行了一些 Google 搜索,但到目前为止没有任何帮助。
我很想听听你的意见。
问候
//编辑:这就是我调用函数的方式:
AuthController.validate(req.headers['api-token'], function(err, decoded){
if(err){ console.log('Error: ', err);
res.status(401); next();
} else if(decoded) {
console.log('Success: ', decoded);
next();
}
})
最佳答案
在 jwt-Example 中,verify
的第三个参数是一个函数(使用函数表达式创建)。
在您的代码中,第三个参数是返回值 或调用cb(err, decoded)
。 cb
函数可能会返回一个函数,但是 err
是您传递给它的一个变量。
如果你想使用一个名为cb
的函数然后定义它然后传递函数:
function cb(err, decoded) {
// do stuff with err and/or decoded
}
jwt.verify(token, secretToken, cb);
关于javascript - 如何在自己的函数中定义回调函数? Node JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24479854/