这是我的app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const app = express();
app.use(cors());
//Mongodb connection
mongoose.connect("mongodb://localhost/expressWithAngular")
.then(() => {
console.log("mongodb connected");
})
//bodyparser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//load routes
const users = require("./routes/users");
//include passport
require("./config/passport")(passport);
// use routes
app.use('/user' , users);
app.get('' ,(req,res) => {
res.send('home');
})
const port = 5000;
app.listen(port , () => {
console.log(`server is running in port ${port}`);
})
这是我的用户路由route / user.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
//user model init
require('./../models/User');
const User = mongoose.model('users');
router.post('/login' , (req,res,next)=>{
console.log("bodyparser" ,req.body);
passport.authenticate('local',{
session: false
},function(req,res,next){
console.log(res);
})
})
module.exports =路由器;
这是我的config / passport.js
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const User = mongoose.model('users');
module.exports = function(passport){
passport.use(new LocalStrategy(
{
usernameField : 'email'
},
function(email,password,done){
console.log(email);
}
))
}
-我正在尝试将我的卑鄙应用程序与护照连接 身份验证,我可以将详细信息发送到后端,但是我无法 将价值传递给当地战略 -我不知道我在哪里,当我主持本地策略时 没有打电话,请纠正我丢失的地方
答案 0 :(得分:0)
我相信您的路由器配置有问题。 passport.authenticate
对您来说是generating middleware,但是在您的情况下,您已经将其包装在函数中,因此可以记录输入参数,并且没有将生成的中间件返回给路由器:
router.post('/login' , (req,res,next)=>{
console.log("bodyparser" ,req.body);
passport.authenticate('local',{
session: false
},function(req,res,next){
console.log(res);
})
})
我建议您修改代码以使其像官方文档中的示例一样工作
router.post('/login' , passport.authenticate('local',{
session: false
});
)
如果您确实需要登录req.body
,只需在身份验证之前添加中间件,如下所示:
router.post('/login' , (req, res, next) {
console.log("bodyparser" ,req.body);
next();
},
passport.authenticate('local', {session: false});
)