MOAZ ALI
MOAZ ALI

Reputation: 37

ReferenceError: index is not defined (Node.js, Express.js)

I am basically trying to use express & hbs for rendering pages dynamically. I have also included the essential npm packages. I have also created index.hbs inside views directory but when I try to run my code, I get the following error.

ReferenceError: index is not defined
    at C:\Users\Moaz\Desktop\Node JS Code\web-server\src\app.js:11:14
    at Layer.handle [as handle_request] (C:\Users\Moaz\Desktop\Node JS Code\web-server\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Moaz\Desktop\Node JS Code\web-server\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Moaz\Desktop\Node JS Code\web-server\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Moaz\Desktop\Node JS Code\web-server\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Moaz\Desktop\Node JS Code\web-server\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Moaz\Desktop\Node JS Code\web-server\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Moaz\Desktop\Node JS Code\web-server\node_modules\express\lib\router\index.js:275:10)
    at SendStream.error (C:\Users\Moaz\Desktop\Node JS Code\web-server\node_modules\serve-static\index.js:121:7)
    at SendStream.emit (node:events:376:20)

app.js code: -

const path = require("path");
const express = require("express");

const app = express();
const publicDirectoryPath = path.join(__dirname, "../public");

app.set("view engine", "hbs");
app.use(express.static(publicDirectoryPath));

app.get("", (req, res) => {
  res.render(index);
});

app.listen(3000, () => {
  console.log("Service is up and running successfully!");
});

Screenshot of VS Code directories: -

enter image description here

Upvotes: 1

Views: 1568

Answers (2)

usmancodes
usmancodes

Reputation: 50

You are rendering the index page wrong, you need to pass a string to the render function, try res.render('index'); on line 11.

Secondly your path me be wrong, put the views folder in your src folder and run the application. Or maybe adjust your path according to web-server/views/

Upvotes: 1

BENARD Patrick
BENARD Patrick

Reputation: 30975

You write index as a variable.

Set it as a string :

app.get("*", (req, res) => {
  res.render('index');
});

Upvotes: 1

Related Questions