Dont understand the correct answer for a challenge (Backend)

Hello!

im currently on “Serve Static Assets” section of the “Basic Node and Express” course, the correct answer is the following:

I dont understand why this is the correct anwser, Im being told that express.static(assetPath) serves static assets acting as a middleware, it needs to be used with app.use(routePath, middleware) and routePath is optional, if we dont put anything there then the ‘/’ will be passed.

im currently serving “/views/index.html” to all get requests to the root path (“/”)

app.get("/", (req, res) => {
  res.sendFile(customPath("views/index.html"));
});

if I simply add app.use(express.static(__dirname + "/public")) this should mean that any get request to server_ip:port (which is a request to root “/”) will be served the views/index.html file, and that the /public folder is being exposed too, so why do I need to also add app.use("/public", express.static(__dirname + "/public")); for the answer to be correct?

I dont understand this, im not visiting server_ip:port/public im visiting server_ip:port

1 Like

express.static() tells express how to serve your static assets like CSS and images. res.sendFile() gets attached to a route ("/" in your example) and serves a file in response, views/index.html in your example. Any stylesheets or images referenced in index.html will be served from /public since that is the directory you told express.static() to use. You’re also not visiting /views/index.html (just "/" or maybe index.html) but express is serving that file at the root because that’s where you mapped it.

See the documentation.

Static files and views are separated like this because at some point, you would serve the static files from a regular webserver (nginx, apache, etc.) and only the dynamic files from express.

Thanks for the response

Mmm… Is there any logic behind where to use relative or absolute path? Or is the only way to consult the docs and remember?

In the solution you ought to mix both, if I got it right.

I wonder if the question would arise if in the course text it would be said “default” instead of “optional”. And thanks for explaining!

And the logic is that absolute path was used to indicate actual files in server FS, and relative to indicate route through which they will be accessible by clients of the server.