Passport JS没有提供用户名

时间:2018-07-24 02:40:28

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

侧面说明:我已经检查了Google和堆栈溢出,并且到目前为止没有找到有效的解决方案。除非您知道自己找到的帖子就是解决方案,否则请不要标记重复。似乎存在许多解决方案。

我正在尝试使用passport-localpassport-local-mongoose创建身份验证服务。以下是我的文件,错误消息仅为No username was given。没有其他描述或帮助。

我只包含了每个文件的重要部分。我正在使用/register请求和原始JSON格式(以'email'和'password'作为键)通过邮递员将请求发送到POST路由

app.js

var express = require('express');
var passport = require('passport');
var bodyParser = require('body-parser');
var LocalStrategy = require('passport-local');


// models
var User = require("./models/user");


// express setup
var app = express();

var indexRoutes = require("./routes/api/index");

// body parser setup
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// setup useful variables for configuration

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + "/public"));


// passport setup
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// Use routes
app.use("/", indexRoutes);




var server = app.listen(8080, function() {
  console.log('Express server listening on port ' + server.address().port);
});

user.js

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
const Schema = mongoose.Schema;


const UserSchema = new Schema({
    email: String,
    password: String,
    avatar: String,
    role: String
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

routes / index.js

//handle sign up logic
router.post("/register", function(req, res){
    var newUser = new User({email: req.body.email});
    User.register(newUser, req.body.password, function(err, user){
        if(err){
           console.log("Error: " + err.message);
            req.flash("error", err.message);
            return res.redirect("back");
        }
        passport.authenticate("local")(req, res, function(){
           req.flash("success", "Welcome to my site");
           console.log('User has been created');
           res.redirect("/"); 
        });
    });
});

1 个答案:

答案 0 :(得分:1)

本地护照需要一个usernameField字段名称,如果未提供,则抛出[MissingUsernameError:未提供用户名]。

如果要使用电子邮件或其他方式,则必须指定。在此处检查实施-Passport local mongoose: no username was given error