3

我已经按照这里的代码 - > https://github.com/jaredhanson/passport-local/tree/master/examples/express3为用户添加本地身份验证。

问题是当我尝试添加用户时,

所以我创建了这条路线

app.get('/signup', function(req,res){
  res.render('/signup');
});

app.post('/signup', function(req,res){
  var body = req.body;
  users.push(body);
  res.redirect('/');
});

然后页面是表单

form(method='POST', action='/signup')
 input(type='text', name='username', placeholder='username')
 input(type='text', name='password', placeholder='password')
 button.btn Register

虚拟数据库 这是示例中的数据库

users = [
  {id:1, username: 'test', password:'papapa'}
];

因此,当我通过表单发送信息时,一切正常,但是当我尝试使用新创建的用户登录时,告诉我“错误:无法将用户序列化到会话中”

serializeUser 是这个

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
});
4

2 回答 2

5

The user being pushed in the POST /signup route will not have an ID, which the examples serialization code expects.

Change it to something like this, and it should work.

app.post('/signup', function(req,res){
  var body = req.body;
  body.id = users.length;
  users.push(body);
  res.redirect('/');
});

(Note that this is an example only, and not recommended for "real" apps.)

于 2012-09-27T15:08:21.820 回答
2

我猜您缺少会话序列化程序。查看https://github.com/jaredhanson/passport的“会话”部分。

基本上,您需要两个函数,将当前用户保存到会话中 (passport.serializeUser) 并将其读回 (passport.deserializeUser)。

于 2012-09-27T11:12:19.773 回答