简体   繁体   中英

TypeError: Cannot read property 'name' of undefined Passpor error

I'm making a login and register page. I'm using passport to do the authentication. I'm using mongosse too. Everything is working fine, however I do not know why user.name is undefined. I tried every single solution that I found on stack related with this problem, but it does not match.

router.js

    require('dotenv').config()
}

const bcrypt = require('bcrypt')
const path = require('path');
const express = require('express');
const User = require('../models/user');
const passport = require('passport');
const initializePassport = require('./passport-config')
const flash = require('express-flash')
const session = require('express-session');
const { JsonWebTokenError } = require('jsonwebtoken');
require('./db/mongoose');



const app = express();

const port = process.env.PORT || 3000;
const publicDirectoryPath = path.join(__dirname, '../public');
const viewsPath = path.join(__dirname, '../views');

initializePassport(
    passport,
    async(email)=>await User.findOne({email: email}),
    async(id)=>await User.findById(id).then(console.log())
)


app.set('view engine', 'ejs');
app.set('views', viewsPath);


app.use(express.static(publicDirectoryPath));
app.use(express.urlencoded({extended: false}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session())



app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false
}));

app.get('/registration',(req, res) => {
    res.render('registration.ejs');
})

app.get('/login',(req, res) => {
    res.render('login.ejs')
})

app.get('/menu',(req, res) => {
    res.render('menu.ejs', { name: req.user.name })
})

app.post('/registration', async(req, res) => {
    try{
        const hashedPassword = await bcrypt.hash(req.body.password, 10);
        
        const newUser = new User({
            name: req.body.name,
            email: req.body.email,
            password: hashedPassword
        });

        newUser.save();

        res.redirect('/login');        

    } catch{
        res.redirect('/registration')
    }
})


app.post('/login', passport.authenticate('local', {
    successRedirect: '/menu',
    failureRedirect: '/login',
    failureFlash: true,
}))


app.listen(port, () => {
    console.log('Server is on port 3000');
})



passport-config.js

const bcrypt = require('bcrypt')

function initialize(passport, getUserByEmail, getUserById){
    const authenticateUser = async (email, password, done)=>{
        const user = await getUserByEmail(email)

        if(user == null){
            return done(null, false, {message: 'No existe un usuario con ese email'})
        }


        try{
            
            const matchPassword = await bcrypt.compare(password, user.password)

            if(matchPassword){
                return done(null, user)
            }else{
                return done(null, false, {message: 'Constraseña Incorrecta'})
            }
        }catch(e){
            return done(e);
        }
    }

    passport.use(new LocalStrategy({usernameField: 'email'}, authenticateUser))
    passport.serializeUser((user,done)=> done(null, user.id))
    passport.deserializeUser((id,done)=> {
        return done(null, getUserById(id))})

}

module.exports = initialize

The error is the following:

TypeError: Cannot read property 'name' of undefined at C:\\Users\\Miguel\\Desktop\\RestaurantControl\\src\\router.js:58:45 at Layer.handle [as handle_request] (C:\\Users\\Miguel\\Desktop\\RestaurantControl\\node_modules\\express\\lib\\router\\layer.js:95:5) at next (C:\\Users\\Miguel\\Desktop\\RestaurantControl\\node_modules\\express\\lib\\router\\route.js:137:13) at Route.dispatch (C:\\Users\\Miguel\\Desktop\\RestaurantControl\\node_modules\\express\\lib\\router\\route.js:112:3) at Layer.handle [as handle_request] (C:\\Users\\Miguel\\Desktop\\RestaurantControl\\node_modules\\express\\lib\\router\\layer.js:95:5) at C:\\Users\\Miguel\\Desktop\\RestaurantControl\\node_modules\\express\\lib\\router\\index.js:281:22 at Function.process_params (C:\\Users\\Miguel\\Desktop\\RestaurantControl\\node_modules\\express\\lib\\router\\index.js:335:12) at next (C:\\Users\\Miguel\\Desktop\\RestaurantControl\\node_modules\\express\\lib\\router\\index.js:275:10) at Immediate._onImmediate (C:\\Users\\Miguel\\Desktop\\RestaurantControl\\node_modules\\express-session\\index.js:502 :7) at processImmediate (internal/timers.js:460:21)

router.get('/', checkAuthorization, async (req, res) => {
    const result = await req.user
    res.render('index.ejs', data = { name: result.name}) })

req.user will return promise if you are using passport module. await req.user and async function . I had the same issue and came up with this solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM