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

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