Undefined error despite linking HTML correctly

Viewed 82

I have linked the routes to the html but the html keep showing agentData is not defined. Why is it giving me this error despite linking it correctly. The app.js code is where I link the routes for login and admin. Routes is where the login control where user go based on username and password. I render the html page once they login in routes.js and then in admin.js, is where it gets all the data from mysql database and output as table. As you can see, I did declare agentData in admin.js. However, if I remove the app.get/admin in routes.js, they gv me another error cannot /Get admin error. What should I do?

routes.js


const express = require('express');
const router = express.Router();
const db = require('../server');

router.get("/",  async function (request, response) {
    response.render("login.ejs");
  });

  router.get("/register", async function (req, res) {
    res.render("register.ejs");
  });

  router.post("/login", async function (request, response) {
    const { username, password } = request.body;

    if (username == 2 && password == 2) {
      response.redirect("/admin");
    } 

    else {
      return response.status(401).json({
        message: "Auth fail",
      });
    }
  });

  router.get('/admin', function(req, res, next) {
    console.log('reach page');
    const sql='SELECT * FROM agentavia';
    db.query(sql, function (err, data, fields) {
      console.log(data);
    if (err) throw err;
    res.render('adminhome', { title: 'Agent List', agentData: data});
  });
  });
  
  router.get('/edit/:id', function(req, res, next) {
    const AgentId= req.params.id;
    const sql=`SELECT * FROM agentavia WHERE id=${AgentId}`;
    db.query(sql, function (err, data) {
      if (err) throw err;
      res.render('modifyAgent', { title: 'Agent List', editData: data[0]});
    });
  });
  
  router.post('/edit/:id', function(req, res, next) {
    const id= req.params.id;
      const updateData=req.body;
      const sql = `UPDATE agentavia SET ? WHERE id= ?`;
      db.query(sql, [updateData, id], function (err, data) {
      if (err) throw err;
      console.log(data.affectedRows + " record(s) updated");
    });
    res.redirect('/admin');
  });
  
  module.exports = router;

adminhome.ejs

    <table border="1">
        <tr>
            <th>S.N</th>
            <th>Agent Name</th>
            <th>Agent ID</th>
            <th>AgentStatus</th>
            <th>Edit</th>
        </tr>

        <% if(agentData.length!=0){ var i=1; agentData.forEach(function(data){ %>
        <tr>
            <td><%=i; %></td>
            <td><%=data.agentName %></td>
            <td><%=data.agentID %></td>
            <td><%=data.agentStatus %></td>
            <td><a href="/admin/edit/<%=data.id%>">Edit</a></td>
        </tr>
        <% i++; }) %> <% } else{ %>
        <tr>
            <td colspan="7">No Data Found</td>
        </tr>
        <% } %>
    </table>

modifyagent.ejs

<div class="agent-detail">
   
    <form action="<%=(typeof editData!='undefined')?'/admin/edit/'+editData.id:'/admin/create'%>" method="POST">
          <label>Agent Name</label>
          <input type="agentname" placeholder="Enter Agent Name" name="agentName" required value="<%=(typeof editData!='undefined')? editData.agentName:''%>">
          <label>Agent ID</label>
          <input type="agentID" placeholder="Enter Agent ID" name="agentID" required value="<%=(typeof editData!='undefined')? editData.agentID:''%>">
          <label>Agent Status</label>
          <input type="Agent Status" placeholder="Enter Agent Status" name="agentStatus" required value="<%=(typeof editData!='undefined')? editData.agentStatus:''%>">
          <button type="submit">Submit</button>
        </div>
  </div>
1 Answers

1.Issue in your file extension. it should be adminhome.ejs instead of adminhome.html

Or Another way is to using includes

For How to use with includes Refer this Ejs engine with html not working

this example I have tested on local.It's working fine

app.js

    const express = require('express');
    const app = express();

    // set the view engine to ejs
    app.set('view engine', 'ejs');

    // index page 
    app.get('/', function (req, res) {
        var data = [
            { id: 1,agentName: 'Bloody Mary', agentID: 3,agentStatus: 'yes' },
            { id:2,agentName: 'Martini', agentID: 5 ,agentStatus: 'no'},
            { id:3,agentName: 'Scotch', agentID: 10 ,agentStatus: 'yes'}
        ];


        res.render('index', {
            agentData: data
        });
    });

    app.listen(3000, () => console.log('listening at 3000'));

Index.ejs

    <h2>Loop</h2>

    <table border="1">
        <tr>
          <th>S.N</th>
          <th>Agent Name</th>
          <th>Agent ID</th>
          <th>AgentStatus</th>
          <th>Edit</th>
        </tr>
      
        <% if(agentData.length!=0){ var i=1; agentData.forEach(function(data){ %>
        <tr>
          <td><%=i; %></td>
          <td><%=data.agentName %></td>
          <td><%=data.agentID %></td>
          <td><%=data.agentStatus %></td>
          <td><a href="/agents/edit/<%=data.id%>">Edit</a></td>
        </tr>
        <% i++; }) %> <% } else{ %>
        <tr>
          <td colspan="7">No Data Found</td>
        </tr>
        <% } %>
      </table>

Ejs reference: https://www.npmjs.com/package/ejs

Related