Answer the question
In order to leave comments, you need to log in
How to serve static files and use routing in express.js?
I am new to express.js. I read the official documentation and several guides, but it still remains unclear how to give static files.
My project has a public folder that contains folders with page files, for example home (inside index.html, styles.css and index.js).
To return static files, it is recommended to use middleware.
With this approach, there is no need to use app.get(), since all files will be returned anyway. Plus, the fact that you can get access to files by writing the path directly to /home/index.html is confusing. The
question is how to give static files and use routing at the same time. For example, I want to style a 404 Not Found page. For this I use the functionapp.use(express.static(__dirname + "/public"));
app.get("/*", (req, res) => {
res.sendFile(__dirname + "/public/notFound/index.html");
});
Answer the question
In order to leave comments, you need to log in
In this form, you can give files with styles if you write "app.get" for each, which is somehow not very convenient.
You have an address in "index.html" where you can download css, for this address you either write "app.get" or still make it possible to download static files.
After all, you still want to give these files to the user, without them it will not work. So it's not scary if he can download.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question