Home > front end >  How can I use MySql tables in my view using EJS? I cannot identify what is wrong
How can I use MySql tables in my view using EJS? I cannot identify what is wrong

Time:12-09

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

TypeError: C:\Users\ygor\Documents\VS Code\Digital House\PI-DevNap\src\views\user.ejs:22
    20|                 <a class='photo' href="#"><img src="/images/camera-change.png" alt="Câmera"></a>
    21|                 <div >
 >> 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)

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 >MINHA CONTA</h2>
        <section >
            
            <div >
                <a class='photo' href="#"><img src="/images/camera-change.png" alt="Câmera"></a>
                <div >
                    <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.

CodePudding user response:

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 } )
},

CodePudding user response:

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!

  • Related