我正在尝试通过在node.js应用程序上使用passport.js来实现身份验证,但得到一个
错误请求
当我发布到/ login时返回。
我已经测试过该路线,并且效果很好,但是每次插入passport.authenticate()时都会收到此错误请求错误。
我想念什么?
这是我的代码
empty_dict
const express = require("express");
const app = express();
const bp = require("body-parser");
const User = require("./db").user;
const Investment = require("./db").investment;
const spending = require("./db").spendings;
const reminder = require("./db").reminder;
const session = require("express-session");
const passport = require('passport');
const flash = require("connect-flash");
const LocalStrategy = require("passport-local").Strategy;
require("./config/passport")(passport);
app.use("/", express.static(__dirname + "/Public_static"));
app.use(bp.urlencoded({ extended: true }));
app.use(bp.json());
//Passport Authentication Implementation
app.use(session({ secret: "keyboard cat", resave: true, saveUninitialized: true })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
app.post("/login", passport.authenticate("local"), function(req, res) {
User.findOne({
where: { email: req.body.username }
})
.then(function(user) {
console.log(user);
user._modelOptions.classMethods.test();
})
.catch(function(err) {
console.log(err);
});
});
app.listen(3100, function() {
console.log("Server started on http://localhost:3100");
});
答案 0 :(得分:0)
您可以尝试将password.js文件更改为:
const User = require("../db").user;
const LocalStrategy = require("passport-local").Strategy;
const Promise = require("bluebird");
module.exports = function(passport) {
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) =>
Promise.try(() => User.findById(id))
.asCallback(done)
);
passport.use(new LocalStrategy(
{
passReqToCallback: true // allows us to pass back the entire request to the callback
},
(req, username, password, done) => {
User.findOne({where: { username: username }})
.then(user =>{
console.log("User found")
return done(null, user, {message: 'User found!'});
})
.catch(err => {
console.log(err)
return done('Unauthorized', false, {message: err.message});
})
}
)
);
};