护照js缺少证件

l2s*_*ver 17 passport-local passport.js

现在已经工作了几个小时,非常令人沮丧......

router.post('/',
passport.authenticate('local-signup', function(err, user, info) {
    console.log(err);
}), function(req, res){
    console.log(req);
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ a: 1 }));
});
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我使用了console.log输出{ message: 'Missing credentials' },这让我相信身体解析器没有正确解析正文消息.当我使用这条路线时......

router.post('/',
    function(req, res){
        console.log(req.body);
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({ a: 1 }));
    });
Run Code Online (Sandbox Code Playgroud)

当我使用时console.log,输出为{password: 'password', email: 'email@email.com'},表示req.body变量设置正确且可用.

app.js

var express = require('express');
var app = express();
var routes = require("./config/routes.config");
var models = require("./config/models.config");
var session = require('express-session');
var bodyParser = require('body-parser');

models.forEach(function(model){
    GLOBAL[model] = require('./models/'+model+".model");
});
var passport = require("./config/passport.config");

app.use( bodyParser.urlencoded({ extended: true }) );
app.use(session({ secret: 'simpleExpressMVC', resave: true, saveUninitialized: true  }));
app.use(passport.initialize());
app.use(passport.session());
Run Code Online (Sandbox Code Playgroud)

Aᴍɪ*_*ᴍɪʀ 42

我看到你的req.body包含{password: 'password', email: 'email@email.com'}.email不是护照正在寻找的,而是username.您可以在HTML/JS上更改输入名称,也可以更改passportjs正在查找的默认参数req.body.您需要在定义策略的地方应用这些更改.

passport.use(new LocalStrategy({ // or whatever you want to use
    usernameField: 'email',    // define the parameter in req.body that passport can use as username and password
    passwordField: 'password'
  },
  function(username, password, done) { // depending on your strategy, you might not need this function ...
    // ...
  }
));
Run Code Online (Sandbox Code Playgroud)

  • 最佳答案 非常感谢。 (2认同)

Lhe*_*air 7

我知道这里有很多答案,但这已经是最清楚的了。

来自官方护照文件

Passportjs 文档

“默认情况下,LocalStrategy 希望在名为用户名和密码的参数中找到凭据。如果您的站点希望以不同的方式命名这些字段,则可以使用选项来更改默认值。”

因此,如果您发现自己遇到这个问题,您有两种解决方案(最有可能)。

  1. 在前端将您的身体参数重命名为usernamepassword

  2. 使用以下代码定义您的护照实例如何命名它们:

    passport.use(new LocalStrategy({
        usernameField: 'email', //can be 'email' or 'whateveryouwant'
        passwordField: 'passwd' //same thing here
      },
      function(username, password, done) {
        // ...
      }
    ));
    
    Run Code Online (Sandbox Code Playgroud)


IT *_*ogs 6

在Router.post:

router.post('/', passport.authenticate('local-signup', {
    successRedirect: '/dashboad',
    failureRedirect: '/',
    badRequestMessage: 'Your message you want to change.', //missing credentials
    failureFlash: true
}, function(req, res, next) {
...
Run Code Online (Sandbox Code Playgroud)