Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
passport-local.js

JavaScript
<pre>'use strict';

const passport = require('passport');
const User = require('../models/user');
const LocalStrategy = require('passport-local').Strategy;

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, user);
  });
});

passport.use(
  'local.signup',
  new LocalStrategy(
    {
      usernameField: 'email',
      passwordField: 'password',
      passreqTocallback: true,
    },
    (req, email, password, done) => {
      User.findOne({ email: email }, (err, user) => {
        if (err) {
          return done(err);
        }
        if (user) {
          return done(
            null,
            false,
            req.flash('error', 'User with the email already exists')
          );
        }

        const newUser = new User();
        newUser.username = req.body.username;
        newUser.fullname = req.body.username;
        newUser.email = req.body.email;
        newUser.password = newUser.encryptPassword(req.body.password);

        newUser.save((err) => {
          done(null, newUser);
        });
      });
    }
  )
);



When I run
Shell
nodemon server
and enter the user registration details and click submit, I get the following error on submiting the user registration form as shown below -

Shell
node:events:371
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'username' of undefined
    at /home/prithvi/Desktop/Ideal-table-talk/passport/passport-local.js:39:37
    at /home/prithvi/Desktop/Ideal-table-talk/node_modules/mongoose/lib/model.js:5065:18
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
Emitted 'error' event on Function instance at:
    at /home/prithvi/Desktop/Ideal-table-talk/node_modules/mongoose/lib/model.js:5067:15
    at processTicksAndRejections (node:internal/process/task_queues:78:11)


What I have tried:

I've tried sending the username as parameter to arrow function in localstrategy constructor but, still I get the same error.
Posted
Updated 19-Jul-21 7:32am

1 solution

The error says that on line 39 of passport-local.js you are trying to access a property name username on some object but that object is null.

We can't tell what your line numbers are but it may be this one

newUser.username = req.body.username;


The error is stating that req.body is null. You will have to debug the code to figure out why that is happening.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900