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 /
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.