1

I create a simple express server and serve the static files

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

app.use(express.static('public'));

app.listen(3000, () => {
console.log('Listening on port 3000')
})

When I head to localhost:3000, the index.html in my public directory renders for the route ' / '. I didn't explicitly write the route in my index.js file. How does express know this?

I've tried changing the file name from index.html to random.html and I get an error. CANNOT GET /

R.Lo
  • 21
  • 1

1 Answers1

1

As mentioned in the comments, app.use(express.static('public')) is responsible for this. This will essentially serve all files in the public folder you have in the project. If you have an index.html in the public folder, then that will be served at the / endpoint automatically. This is a convention that most websites follow, and is documented in this SO post.

Here is the relevant documentation on express.static(...): https://expressjs.com/en/starter/static-files.html

nareddyt
  • 1,016
  • 10
  • 20