3

在提交带有护照的登录表单后,我正在尝试访问 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() 部分时,选中我表单中的复选框并正确提交表单控制台 logs 1

那么,当我还使用 passport.authenticate() 时,如何访问 POST 参数呢?

4

1 回答 1

1

Haven't used passport so far but here are two things that might cause your problem

1. Your form doesn't have an action attribute

Therefore the form doesn't know where to send the data. Try the following

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

2. POST variables in express are attached to the req.body object

So instead of

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

use

console.log(req.body.username);

Make sure you have the bodyParser in your express config.

req.param is used when you want to access dynamic routes

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

// GET /login/john => 'john'
于 2013-01-09T18:59:29.613 回答