2013-01-09 37 views
2

我试图在提交护照登录表单后访问POST参数。我的形式如下:如何访问node.js护照身份验证的POST数据?

<form method="post"> 
    <input name="username"> 
    <input name="password"> 
    <input type="checkbox" name="remember" value="1"> 
    <input type="submit"> 
</form> 

的(工作)快递航线/回调:

app.post(
    '/login', 
    passport.authenticate('local', { 
     failureRedirect: '/login', 
     failureFlash: true, 
     badRequestMessage: 'Please enter your account credentials to login.' 
    }), 
    function(req, res) { 
     console.log(req.param('remember')); 
     if(req.isAuthenticated(req, res)) { 
      res.redirect('/dashboard'); 
     } else { 
      var errors = req.flash('error'); 
      if(errors) { 
       assign['errors'] = errors; 
      } 
      res.render('login.html', {errors: errors}); 
     } 
    } 
); 

登录工作正常,一切都很酷。但是:req.param('remember')总是undefined。当我删除passport.authenticate()部分时,请选中我的表单中的复选框并正确提交表单控制台日志1

那么我怎样才能访问POST参数,当我也使用passport.authenticate()?

+0

你的代码似乎工作对我来说,尝试升级您的快递和护照库使用!我测试过了。 – drinchev

+0

啊,我的代码中有一个更高的“/ login”路径。现在req.param('remember')工作正常,但我仍然无法访问该路由中的用户名和密码字段。当我尝试访问req.param('用户名')或req.param('密码')时,用户名和密码都是未定义的。检查后护照是否可能删除参数? –

+0

nope,参数传递不变......调试你的整个'''req'''变量:'''console.log(req)''' – drinchev

回答

2

没有使用护照到目前为止,但这里有可能导致您的问题两件事情

1.你的形式不具有action属性

因此,形式不知道在哪里发送数据。尝试在表达以下

<form method="post" action="/login"> 
    <input name="username"> 
    <input name="password"> 
    <input type="checkbox" name="remember" value="1"> 
    <input type="submit"> 
</form> 

2. POST变量附着在req.body对象

所以不是

console.log(req.param('remember')); 

使用

console.log(req.body.username); 

请确保您有bodyParser在你的快速配置。

req.param当你要访问动态路由

app.get('/login/:user', function(req, res) { 
    console.log(req.params.user) 
}) 

// GET /login/john => 'john' 
+0

对不起,我忘记了我的例子中的action属性。在我的模板当然存在;) –

+0

配置expressParser仍然需要吗? – ahsteele