护照本地注册表单的Node.js app.post不起作用

时间:2017-02-28 12:22:14

标签: node.js passport.js passport-local

我正在尝试设置护照本地登录,但表单在提交时不会执行任何操作。

我的app.js代码:

var express = require('express');

var app = express();
app.use(express.static(__dirname + '/public'));
var credentials = require('./credentials.js');
app.use(require('cookie-parser')(credentials.cookieSecret));
app.use(require('body-parser').urlencoded({extended: false}));
var session = require('express-session');
app.use(session({
    resave: false,
    saveUninitialized: true,
    secret: 'keyboard cat'
}));
var passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());

app.disable('x-powered-by');

var handlebars = require('express-handlebars').create({defaultLayout:'main'});

app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

app.set('port', process.env.PORT || 3000);
app.post('/login', function(req, res){console.log("body parsing", req.body)});

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

用于登录的表单html at / login:

<form action="/login" method="post">
    <div>
        <label>Username:</label>
        <input type="text" name="username"/>
    </div>
    <div>
        <label>Password:</label>
        <input type="password" name="password"/>
    </div>
    <div>
        <button type="submit">Submit</button>
    </div>
</form>

当我填写用户名和密码时,没有任何内容从帖子请求打印到控制台。我有什么不对?

2 个答案:

答案 0 :(得分:1)

您必须序列化和反序列化用户详细信息才能对用户进行身份验证。

此处和示例。

<强> services.js

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');

//serialize and deserialize
passport.serializeUser(function(user, done) {
    done(null, user._id);
});

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

//middleware
passport.use('local-login', new LocalStrategy({
    usernameField: 'email',
    password: 'password',
    passReqToCallback: true
}, (req, email, password, done) => {
    User.findOne({ email: email.toLowerCase() }, function(err, user) {
        if (err) return done(err);

        if (!user) {
            return done(null, false, req.flash('loginMessage', 'No user has been found'));
        }

        if (!user.comparePassword(password)) {
            return done(null, false, req.flash('loginMessage', 'Oops! Wrong Password.'));
        }
        return done(null, user);
    });
}));

//custom function to validate
exports.isAuthenticated = function(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/login');
}

并且一旦进行序列化,您必须将该过程实际应用于路由器。即,使用户详细信息输入护照。

在您的路由器文件中:

const passportConfig = require('services.js');

然后您只需通过req.user

访问数据即可

答案 1 :(得分:0)

我发现删除此AMP js脚本可以解决问题。由于某种原因,它打破了帖子请求。

<script async src="https://cdn.ampproject.org/v0.js"></script>