Index.html is not loaded in the browser

I am new to Node and Express and I am stuck on the basic code.

This is my code

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

const app = express();
const router = express.Router();

let port = process.env.port || 3000;


router.get("/", (req, res)=>{
   console.log("hello world");
   res.sendFile('index.html', {root: path.join( __dirname, '/public/')})


app.listen(port, (err)=> {
        return(console.log("i am listening"));
    console.log(`listening to the port ${port}`);

This is my project’s directory structure:

enter image description here

When I remove the option in the express.static( ), it opens but the public has index.html but I want to open with res.sendFile( ) because I am learning.

Thank you in advance !!!

2 thoughts on “Index.html is not loaded in the browser”

  1. Well, express.static() already attempts to match / to index.html in the directory you are pointing at. If you want the / custom route to have priority over your express.static() route, then just move that route definition before your express.static() route.

    Or, alternatively, you can turn that express.static() feature off so express.static won’t look for index.html on a / route request, with an option as described in the doc here:

    app.use(express.static('public'), {index: false});

Leave a Comment