Express - Serve Static Assets: Why doesn't the first argument of app.use take the absolute path?

Hi,

Just a quick technical question.

While completing this challenge, I discovered that the stylesheet won’t load correctly if you pass app.use the absolute path (__dirname + "/public") as opposed to just "/public" for the first argument.

I was wondering why this is? Just out of curiosity. I tried searching online but couldn’t find anything about this in documentation. Maybe I’m just not looking for the right thing?

You got it:

app.use("/public", express.static(__dirname + "/public")); (works)

app.use((__dirname + "/public"), express.static(__dirname + "/public")); (does not work)

The folder that is given to express.static becomes the base directory.

If you do not mount it to /public the path in the HTML file /public/style.css is wrong as it would just be ./style.css (or just style.css).

For example, for the file path

/public/css/styles.css

Using…

app.use(express.static('public'));

…would give you this path to the file.

http://localhost:3000/css/style.css

The first argument to app.use is a virtual mount path. For example, we can use static, which is a folder that does not exist.

app.use('/static', express.static('public'))

Now the CSS file inside the public folder can be used as if it was in a static folder

HTML

<link rel="stylesheet" href="/static/style.css">

2 Likes