bradtraversy / meanauthapp

Complete MEAN stack app with authentication
242 stars 152 forks source link

Authenticate error in Postman #48

Open michaellescano opened 5 years ago

michaellescano commented 5 years ago

So I 've trying to follow along and I've been stuck with this error when entering the username and password to localhost:3000/users/authenticate in Postman. I get the following error:

Server Started on http://localhost:3000 Press CTRL + C to stop server Connected to database mongodb://localhost:27017/mean-app TypeError: Cannot read property 'username' of undefined at router.post (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\routes\users.js:28:29) at Layer.handle [as handle_request] (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\layer.js:95:5) at next (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\layer.js:95:5) at c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:281:22 at Function.process_params (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:335:12) at next (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:275:10) at Function.handle (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:174:3) at router (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:47:12) at Layer.handle [as handle_request] (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:317:13) at c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:284:7 at Function.process_params (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:335:12) at next (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:275:10) at cors (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\cors\lib\index.js:188:7)

Here is my code for users.js

const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/database');
const User = require('../models/user');

// Register
router.post('/register', (req, res, next) => {
  let newUser = new User ({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, user) => {
    if(err) {
      res.json({success: false, msg: 'Failed to register user'});
    } else {
      res.json({success: true, msg: 'User registered'});
    }
  });
});

//authenticate
router.post('/authenticate', (req, res, next) => {
  const username = req.body.username;
  const password = req.body.password;

  User.getUserByUsername(username, (err, user) => {
      if (err) throw err;
      if (!user) {
          return res.json({ success: false, msg: 'user not found' });
      }
      User.comparePassword(password, user.password, (err, isMatch) => {
          console.log('test');
          if (err) throw err;
          if (isMatch) {
              const token = jwt.sign({data: user}, config.secret, {
                  expiresIn: 604800
              });
              res.json({
                  succes: true,
                  token: 'JWT ' + token,
                  user: {
                      id: user._id,
                      name: user.name,
                      username: user.username,
                      email: user.email
                  }
              })
          }
          else {
              return res.json({ succes: false, msg: 'wrong password' });
          }
      })

  })
})

// Profile
router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
  res.json({user: req.user});
});

module.exports = router;

Here is my passport.js:

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');

module.exports = function(passport){
  let opts = {};
  opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
    User.getUserById(jwt_payload.data._id, (err, user) => {
      if(err){
        return done(err, false);
      }

      if(user){
        return done(null, user);
      } else {
        return done(null, false);
      }
    });
  }));
}

Any ideas?

tomcatbuzz commented 5 years ago

Did you compare your files to Brad's repo. I would also look at the Issues page and comments. Many people have had the same error and posted replies have helped them. There were changes from the original creation of the Video. The Repo merged some changes before. I would simply check and compare files and read the issues pages. You might find your answer.  On Thursday, June 6, 2019, 4:28:33 AM EDT, Michael Lescano notifications@github.com wrote:

So I 've trying to follow along and I've been stuck with this error when entering the username and password to localhost:3000/users/authenticate in Postman. I get the following error:

Server Started on http://localhost:3000 Press CTRL + C to stop server Connected to database mongodb://localhost:27017/mean-app TypeError: Cannot read property 'username' of undefined at router.post (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\routes\users.js:28:29) at Layer.handle [as handle_request] (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\layer.js:95:5) at next (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\layer.js:95:5) at c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:281:22 at Function.process_params (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:335:12) at next (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:275:10) at Function.handle (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:174:3) at router (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:47:12) at Layer.handle [as handle_request] (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:317:13) at c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:284:7 at Function.process_params (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:335:12) at next (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:275:10) at cors (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\cors\lib\index.js:188:7)

Here is my code for users.js const router = express.Router(); const passport = require('passport'); const jwt = require('jsonwebtoken'); const config = require('../config/database'); const User = require('../models/user');

// Register router.post('/register', (req, res, next) => { let newUser = new User ({ name: req.body.name, email: req.body.email, username: req.body.username, password: req.body.password });

User.addUser(newUser, (err, user) => { if(err) { res.json({success: false, msg: 'Failed to register user'}); } else { res.json({success: true, msg: 'User registered'}); } }); });

//authenticate router.post('/authenticate', (req, res, next) => { const username = req.body.username; const password = req.body.password;

User.getUserByUsername(username, (err, user) => { if (err) throw err; if (!user) { return res.json({ success: false, msg: 'user not found' }); } User.comparePassword(password, user.password, (err, isMatch) => { console.log('test'); if (err) throw err; if (isMatch) { const token = jwt.sign({data: user}, config.secret, { expiresIn: 604800 }); res.json({ succes: true, token: 'JWT ' + token, user: { id: user._id, name: user.name, username: user.username, email: user.email } }) } else { return res.json({ succes: false, msg: 'wrong password' }); } })

}) })

// Profile router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => { res.json({user: req.user}); });

module.exports = router;

Here is my passport.js: const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; const User = require('../models/user'); const config = require('../config/database');

module.exports = function(passport){ let opts = {}; opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken(); opts.secretOrKey = config.secret; passport.use(new JwtStrategy(opts, (jwt_payload, done) => { User.getUserById(jwt_payload.data._id, (err, user) => { if(err){ return done(err, false); }

  if(user){
    return done(null, user);
  } else {
    return done(null, false);
  }
});

})); }

Any ideas?

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub, or mute the thread.