Node.js Sequelize.js:findById()未找到数据
我想验证传入令牌,并尝试按Id查找用户:Node.js Sequelize.js:findById()未找到数据,node.js,sequelize.js,Node.js,Sequelize.js,我想验证传入令牌,并尝试按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
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;
}
但我得到“返回错误”。我查看debuggindg的foundUser变量,它有一条消息
'引用错误:未定义foundUser'
在控制台中,我可以看到查询:
执行(默认):选择“id”、“用户名”、“电子邮件”、“密码”,
“createdAt”、“updatedAt”从“用户”改为“用户”,其中“用户”。“id”=
2;
我有一个db中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不是函数
确保异步记住 因为是异步的!您将首先得到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)
});
一定有一些代码你还没有发布。从您的
returnfounduser
行判断,我感觉您误解了异步编程的工作原理。如果在返回之前添加console.log(foundUser)
,您会得到什么?我不太懂如何编写异步代码。我试图改变我的问题并添加代码。这里有很多关于JavaScript异步编程的Stackoverflow解释。这可能是这里问得最多的问题,所以搜索它,你会得到很多结果。在您的情况下,在数据库中查找用户需要时间,因此您需要传递一个函数(在.then()
方法中),当出现结果或错误时(在将来的某个地方)将调用该函数。嗨,伙计们,你们不应该这样写,你不明白我的意思meant@Svenskunganka这个原则我理解。我还是不懂箭头的语法。.catch(()=>{and.then((值)=>{)调用了“expression expected”。此方法返回db.users.findById()导致错误()