0
Put this piece of code:
const express = require("express");
const app = express();
app.use(express.static(__dirname));
But I strongly recommend serving static files inside a folder, for more code organization:
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.listen(3000);
The . html files will be inside the folder /public
.
In the two examples, you will access http://localhost:3000
But, if you want to access, for example: http://localhost:3000/site, you will use app.use("/site", express.static(path.join(__dirname, "public")));
, thus:
const express = require("express");
const path = require("path");
const app = express();
app.use("/site", express.static(path.join(__dirname, "public")));
app.listen(3000);
Access http://localhost:3000/site
In the first argument of the function use
, is the endpoint address that will be accessed by the user, and in the second argument is the location of the static files that will be served to the client.
To better understand, if you put "/site/api/v2" instead of "/site", you will access the following URL: http://localhost:3000/site/api/v2
and if you put path.join(__dirname, "public", "static")
, in your project you will put the static files in /public/static
(files .html
, .css
, .js
, among others)
That’s it. :)
There is no route rendering this page. There is no route for this index.html. For example
app.get('/index', function(req, res) {
 res.sendfile('public/index.html')
})
.– Chance
I made this route app.get('/', Function(req, res) { res.sendfile('./index.html') }) and when I try to access localhost:3000/index.html keeps giving the same error
– Alexandre
From a searched how it loads pure html file, I make use of view engine, so it’s not the same thing to render html. You have to load the public folder into the express to load what’s inside it as well.
– Chance
Following the friend’s comment above, you should access "http://localhost:3000/index" and not "http://localhost:3000/index.html". The route that was created is "/index" and not "/index.html".
– Diego Schmidt