【发布时间】:2023-03-23 04:22:01
【问题描述】:
我是在节点 js 中开发 api 的新手。最近我开始在一个节点 js 应用程序上工作,我使用 jwt 令牌进行身份验证。
我的 jwt 验证函数如下
var jwt = require('jsonwebtoken');
var config = require('../config.js')
var JwtValidations = {
//will validate the JTW token
JwtValidation: function(req, res, next, callback) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secret, callback);
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}
}
module.exports = JwtValidations;
我向这个函数传递一个回调函数,以便如果 jtw 令牌验证通过,我可以为请求提供服务。下面是向系统添加用户的一个示例
// addmin a user to the database
router.post('/add', function(req, res, next) {
JwtValidations.JwtValidation(req, res, next, function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
retrunval = User.addUser(req.body);
if (retrunval === true) {
res.json({ message: "_successful", body: true });
} else {
res.json({ message: "_successful", body: false });
}
}
})
});
// addmin a user to the database
router.put('/edit', function(req, res, next) {
JwtValidations.JwtValidation(req, res, next, function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
User.UpdateUser(req.body, function(err, rows) {
if (err) {
res.json({ message: "_err", body: err });
} else {
res.json({ message: "_successful", body: rows });
}
});
}
})
});
正如您在这两个函数中看到的那样,我正在重复相同的代码段
return res.json({ success: false, message: 'Failed to authenticate token.' });
当且仅当JwtValidations.JwtValidation 不包含任何错误时,我如何避免这种情况并调用回调函数
【问题讨论】:
标签: javascript node.js express callback