Reputation: 15
I have seen some code online and was wondering how the index.HTML was getting rendered when we are not using any app.get()
the public file structure follow like this:
css(folder), js(folder), chat.html, index.html,
const path = require('path');
const express = require('express');
const app = express();
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Upvotes: 0
Views: 114
Reputation: 707926
When an incoming request matches a directory name that express.static()
is configured for, then express.static()
will look for an index.html
file in that directory and, if found, will serve it.
You can see this feature mentioned here in the doc, in the index
option you can pass express.static()
that allows you to specify the name of the index.html
file to look for (default value is index.html
) or you can set it to false
to disable the feature.
So, in your code example, with this:
app.use(express.static(path.join(__dirname, 'public')));
an incoming http request for /
will look for public/index.html
and, if found, will serve it automatically. Similarly a request for /foo
will look first for /public/foo
and if that is present and is a directory, then it will look for public/foo/index.html
and, if found, will serve it.
Upvotes: 1