NodeJS 未调用Passport js本地策略

c9qzyr3d  于 2023-04-29  发布在  Node.js
关注(0)|答案(2)|浏览(130)

这是我的应用程序。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}`);
})

这是我的用户路由路由/用户。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);
    })
})

router = router;
这是我的配置/护照。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);
       }
    ))
}
  • 我试图通过passport身份验证连接我的平均堆栈应用程序,我能够将详细信息发送到后端,但我无法将值传递到本地策略-我不知道我在哪里丢失,当我安慰本地策略未被调用时,请更正我在哪里丢失
vq8itlhq

vq8itlhq1#

我认为您的路由器配置有问题。passport.authenticate正在为您生成中间件,但在您的情况下,您将其 Package 在函数中,以便您可以记录输入参数,并且您尚未将生成的中间件返回给路由器:

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});
)
bvjxkvbb

bvjxkvbb2#

我也遇到了同样的问题,结果是当函数没有收到正确的参数时,它就不会被调用。首先要确保在请求中。body是正确的数据。那么,如果你使用localStrategy,这个策略需要两个参数***,用户名和密码。但它只接收usernameField作为电子邮件。必须指定passwordField**参数,

passport.use(new LocalStrategy({
  usernameField : 'email',
  //here will be the name of the password field in your form
  passwordField : 'userPassword'
}))

只有这样才能调用本地策略。默认情况下,localStrategy查找值“username”和“password”

相关问题