我想验证传入的 token ,并尝试通过 ID 查找用户:
module.exports = function (req) {
var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
db.users.findById(decodeToken.id).then(function (foundUser) {
//It's example checking for self-learning
if (foundUser.username == req.cookies.username) {
return foundUser;
}
//Or more logic for token authentication
}), function (error) {
return error;
}
但我得到“返回 false”。我查看 debuggindg 的foundUser 变量,它有消息
'Reference Error: foundUser is nor defined'
在控制台中我可以看到查询:
Executing (default): SELECT "id", "username", "email", "password", "createdAt", "updatedAt" FROM "users" AS "users" WHERE "users"."id" = 2;
我在数据库中有 id=2 的用户。 为什么不起作用?
<小时/>添加:
我尝试了MWY的修改示例:
module.exports = function (req) {
var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
findUserById().then(function(foundUser) {
//It's example checking for self-learning
if (foundUser.username == req.cookies.username) {
return foundUser;
}
//Or more logic for token authentication
}), function (error) {
return error;
}
function findUserById() {
return db.users.findById(decodeToken.id).then(function (foundUser) {
return foundUser;
}), function (error) {
return error;
}
}
}
并得到错误:
TypeError: findUserById(...).then is not a function
最佳答案
一定要记住异步
因为异步!你会先得到false,然后得到结果!
所以你可以这样写,在 ty.js 文件中
module.exports = function (req) {
var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
return db.users.findById(decodeToken.id).then(function (foundUser) {
//It's example checking for self-learning
if (foundUser.username == req.cookies.username) {
return foundUser;
}
//Or more logic for token authentication
}).catch(function (err) {
return err;
})
};
在tu.js文件中:
var user = require('./ty');
user().then(function (result) {
//search findById result
console.log(result)
});
关于node.js - Sequelize.js:findById() 未找到数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173383/