-1

I am new on Node.js and I have app.js file like:

const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port);
console.log(`App running on http://localhost:${port}`);

I also have index.html file in the same folder with app.js. Here there is a HTML5 website. When I run the project I can see Hello World text in browser, How can I show this HTML file from my app.js so when I deploy it, it should show me responsive HTML file instead of Hello World?

I tried

app.get('/',function(req,res) {
    res.sendFile('index.html');
  });

But didn't see a difference.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • "But didn't see a difference." — Did you restart the server after you changed its source code? – Quentin Nov 06 '22 at 21:22

2 Answers2

-1

To make your code example work you'll need to specify an absolute path, try using this:

res.sendFile(__dirname + "/index.html");

Another way would be to use EJS (https://ejs.co/)

In your example, you could do the following:

Install EJS:

npm install ejs

Set the View Engine to EJS:

app.set('view engine', 'ejs')

- Move your index.html file to a folder called "views" and also rename the file to index.ejs views/index.ejs

In your app.get() handler, use:

res.render('index')

Final Result:

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

app.set("view engine", "ejs");

const port = 8080;

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

app.listen(port, () => {
  console.log(`App running on http://localhost:${port}`);
});

(note: I also moved your console.log to inside app.listen)

Jacob Cambell
  • 277
  • 1
  • 4
-1

I found this on another stack overflow question, it should work

fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
    res.send(text);
});
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
Jaz
  • 55
  • 5