提醒一下,这个项目是基于Glitch的以下入门项目构建的,或者是从GitHub克隆的。序列化和反序列化是身份验证方面的重要概念。序列化对象意味着将其内容转换为一个小键,基本上可以将其反序列化为原始对象。这使我们能够知道与服务器通信的人,而无需在每次请求新页面时发送用户名和密码等身份验证数据。要正确设置它,我们需要一个序列化函数和一个反序列化函数。在护照中,我们使用passport.serializeUser( OURFUNCTION )
和passport.deserializeUser( OURFUNCTION )
创建它们。使用2个参数调用serializeUser,完整的用户对象和护照使用的回调。在回调中返回应该是唯一的键来标识该用户 - 最容易使用的用户是对象中的用户_id,因为它应该是MongoDb生成的唯一用户。类似地,使用该密钥和护照的回调函数调用deserializeUser,但这次我们必须获取该密钥并将用户完整对象返回到回调。要进行查询搜索Mongo _id,您必须创建const ObjectID = require('mongodb').ObjectID;
,然后使用它调用new ObjectID(THE_ID)
。一定要将MongoDB添加为依赖项。您可以在以下示例中看到: passport.serializeUser((user,done)=> {
done(null,user._id);
});
passport.deserializeUser((id,done)=> {
db.collection( '用户')。findOne(
{_id:new ObjectID(id)},
(错误,doc)=> {
完成(null,doc);
}
);
});
注意:这个deserializeUser将抛出一个错误,直到我们在下一步中设置数据库,因此注释掉整个块并在函数deserializeUser中调用done(null, null)
。当您认为自己已经做对时,请提交您的页面。
## Instructions