Search code examples
node.jsmongoosepassport.jspassport-local

Passport JS no username was given


Side note: I have checked google and stack overflow and no solution I have found so far has worked. Please do not mark duplicate unless you know for a fact that your post you found is the solution. Seems like many solutions exist.

I am trying to create an auth service using passport-local and passport-local-mongoose. Below are my files and my error message is just No username was given. Nothing else descriptive or helpful.

I have only included the important parts of each file. I am sending the request via postman to the /register route using a POST request and raw JSON format with 'email' and 'password' as the keys

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("/"); 
        });
    });
});

Solution

  • Passport local expects a usernameField name and throws a [MissingUsernameError: No username was given] if its not provided.

    If you want email or anything else instead, then you have to specify that. Check an implementation here -Passport local mongoose: no username was given error