I keep getting a type error when I try to render an EJS page… ,can someone have a look?

Issue

Here is the index.js code

    enter code here
    CODE
    const express = require('express');
    const app = express();
    const path = require('path');

    app.use(express.urlencoded({ extended: true }))enter code here // for parsing application/x- 
    www-form-urlencoded
    app.use(express.json()) // for parsing application/json
    app.set('views', path.join(__dirname, 'views'))
    app.set('view engine','ejs')

    const comments = [
        { 
            id:1,
            username: 'tom',
            comment: 'lol'
        },
        {
            id:2,
            username: 'joy',
            comment : 'lmao'
        },
        {
            id:3,
            username: 'ango',
            comment: 'lwkm'
        },
        {
            id:4,
            username: 'shaiyen',
            comment: 'leemao'
        }
    ]

    app.get('/comments',(req,res) => {
        res.render('comments/index',{comments})
    })
 
    app.get('/comments/new', (req,res) =>{
        res.render('comments/new')
    })

    app.post('/comments',(req,res) =>{
        const {username,comment} = req.body;
        comments.push({username,comment})
        res.redirect('/comments');
    })

    app.get('/comments/:id',(req,res) =>{
        const{id}= req.params;
        const comment = comments.find(c => c.id === parseInt(id));
        res.render('comments/show',{comment})
    })

    app.get('/tacos',(req,res) => {
        res.send("GET /tacos response")
    })

    app.post('/tacos', (req,res) =>{
        const  {meat, qty} = req.body;
        res.send(` here are your ${meat} and ${qty} tacos`)
    })

    app.listen(3000, () => {
        console.log("listening on port 3000")
    })

While here is the html file

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Show</title>
</head>
<body>
    <h1>Your comment<%= comment.id %> </h1>
    <h2><%= comment.comment - comment.username %> </h2>
</body>
</html>

It keeps showing this error[TypeError: C:\Users\BARINE\Downloads\game\stuff\getpost\views\comments\show.ejs:10
8|

9| <body>

10|

<%= comment.id %>

11|     <h2><%= comment.comment - comment.username %> </h2>

12| </body>

13| </html>

Cannot read properties of undefined (reading ‘id’)
at eval ("C:\Users\BARINE\Downloads\game\stuff\getpost\views\comments\show.ejs":12:34)
at show (C:\Users\BARINE\Downloads\game\stuff\getpost\node_modules\ejs\lib\ejs.js:703:17)
at tryHandleCache (C:\Users\BARINE\Downloads\game\stuff\getpost\node_modules\ejs\lib\ejs.js:274:36)
at View.exports.renderFile [as engine] (C:\Users\BARINE\Downloads\game\stuff\getpost\node_modules\ejs\lib\ejs.js:491:10)
at View.render (C:\Users\BARINE\Downloads\game\stuff\getpost\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\BARINE\Downloads\game\stuff\getpost\node_modules\express\lib\application.js:657:10)
at Function.render (C:\Users\BARINE\Downloads\game\stuff\getpost\node_modules\express\lib\application.js:609:3)
at ServerResponse.render (C:\Users\BARINE\Downloads\game\stuff\getpost\node_modules\express\lib\response.js:1039:7)
at C:\Users\BARINE\Downloads\game\stuff\getpost\index.js:50:9
at Layer.handle [as handle_request] (C:\Users\BARINE\Downloads\game\stuff\getpost\node_modules\express\lib\router\layer.js:95:5)]1

Solution

Hey So I Just Ran Your Code And Everything Seems to be in order

Now This Error Which You Got

Cannot read property 'id' of undefined
    at eval

Is Beacuse the parameter you passing as id don’t exist in the comments array

So when this route is called

const comment = comments.find(c => c.id === parseInt(id)); //comment == undefined

and thou the error and Ejs compile throw an eval error

Since you new try using try and catch

so your code should be like

app.get('/comments/:id',(req,res) =>{
   try{
    const{id}= req.params;
    const comment = comments.find(c => c.id === parseInt(id));
    if(comment){
      res.render('comments/show',{comment})
    }else{
      res.status(404).send("Resource Not Found")
     }
    }catch (err){
      // How you would like to handle your error 
    }
})

Answered By – Ogoh.cyril

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published