skip to Main Content

When I try to use the data in my EJS page it gives this error:

TypeError: C:UsersygorDocumentsVS CodeDigital HousePI-DevNapsrcviewsuser.ejs:22
    20|                 <a class='photo' href="#"><img src="/images/camera-change.png" alt="Câmera"></a>
    21|                 <div class="hello-user">
 >> 22|                     <h3>Olá <%= user.name %>
    23|
    24|                     </h3>
    25|                     <h6>

This is the controller code in question:

index: async (req, res) => {
  
      const user = await req.user;
  
      if (user) {
        return res.redirect('/account');
      }
  
      return res.render('user', { user } )
    },

This is the Session creation code:

login: (req, res) => {
      const { email, password, remember } = req.body
      const hasToRemember = !!remember;
      
      const user = users.find(user => user.email === email)
    
      if (!user) {
        return res.render('login', {
          error: 'Username or password incorrect.'
        })
      }
  
      if (!bcrypt.compareSync(password, user.password)) {
        return res.render('user', {
          error: 'Username or password incorrect.'
        })
      }
  
      req.session.email = user.email;
      
      if (hasToRemember) {
        res.cookie('user', user.email, { maxAge: 5000 });
      }
      
      res.redirect('/account')
    },  

Router:

router.get('/', cookie, usersController.index)

MySQL: (https://i.stack.imgur.com/BsJxw.png)

Migration:

module.exports = {
  async up (queryInterface, Sequelize) {
    await queryInterface.createTable('users', {
      id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
      },
      name: {
        type: Sequelize.STRING,
        allowNull: false
      },
      email: {
        type: Sequelize.STRING(100),
        allowNull: false,
        unique: true
      },
      password: {
        type: Sequelize.STRING(1000),
        allowNull: false
      }
    })
  },

  async down (queryInterface, Sequelize) {
    await queryInterface.dropTable('users')
  }

Middleware (cookie):

const getInfoDatabase = require('../utils/getInfoDatabase')

const users = getInfoDatabase('users')

function cookie(req, res, next) {
  const email = req.cookies.user || req.session.email;

  if (Boolean(email)) {
    const userSession = users.find(user => user.email === email)
    req.user = userSession
  }

  return next()
}

module.exports = cookie

EJS code:

<body>
    <%- include('partials/header') %>
    <main>
        <h2 class="myaccount">MINHA CONTA</h2>
        <section class="account-infos">
            
            <div class="history">
                <a class='photo' href="#"><img src="/images/camera-change.png" alt="Câmera"></a>
                <div class="hello-user">
                    <h3>Olá <%= user.name %>
                        
                    </h3>

I expected it to capture the session information in

const user = await req.user;
  
      if (user) {
        return res.redirect('/account');
      }
  
      return res.render('user', { user } )

but I think this is not happening.

Sorry if this has been answered before, it’s my first question and I haven’t found a solution looking at other threads.

2

Answers


  1. The user shows as undefined in the EJS page so to fix this you just implement this code.

    index: async (req, res) => {
      const user = await req.user;
      
      if (user) {
        return res.redirect('/account');
      }
    
      // Pass the user object to the EJS page
      return res.render('user', { user } )
    },
    
    Login or Signup to reply.
  2. Alright after revising this i have understood my mistake in my previous awnser. Basically tt looks like the issue is with the user object that is being passed to the EJS view. The user object is not defined, so when the EJS view tries to access the name property of user, it fails with a TypeError.
    To fix this issue, you can just make sure that the user object is defined and has a name property. For example this could work:

    login: (req, res) => {
      const { email, password, remember } = req.body;
      const hasToRemember = !!remember;
    
      const user = users.find(user => user.email === email);
    
      if (!user) {
        return res.render('login', {
          error: 'Username or password incorrect.'
        });
      }
    
      if (!bcrypt.compareSync(password, user.password)) {
        return res.render('user', {
          error: 'Username or password incorrect.'
        });
      }
    
      req.session.email = user.email;
      req.user = user; // <-- set the user object on the request
    
      if (hasToRemember) {
        res.cookie('user', user.email, { maxAge: 5000 });
      }
    
      res.redirect('/account');
    },
    

    This way, when the index method in the controller tries to access the user object on the request, it will be defined and will have the properties that are needed by the EJS view.

    Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search