Why is the styles.css not loading in project API & Microservices Serve Static Assets?

If I add the route explicitly, then it works. But I wonder why it doesn’t load the styles.css when I am not mentioning it.

var express = require('express');

var app = express();

//app.use('/public', express.static('./public'));  //this works
app.use(express.static('./public')); // this doesn't work

app.get('/', (req, res, next) => {

res.sendFile(__dirname + '/views/index.html');

});

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36

Challenge: Serve Static Assets

Link to the challenge:

What do the first and second arguments to app.use do? I see the working example takes two arguments and the second only one.

After doing some debugging by putting breakpoints in the dependency modules I finally understood how it’s working.

First of all, app.use([path], callbackFn[, callbackFn]) will consume the prefix if the request url matches. That is, app.use('/public', callbackFn), will simply consume the /public if the GET(in this case) request is /public/style.css. The value of req.url becomes /style.css.

Secondly, express. static(path, [option]) use the provided path parameter as the base path for the static resources and appends to it the req.url value to serve the static assets.

Putting these together, when I use the app.use(express.static('./public')) and the GET request is /public/style.css, the file path becomes ../proj_dir/public/public/style.css, which doesn’t work because the style.css exists in the ../proj_dir/public/.

app.use('/public', express.static('./public')) works because the prefix of the url is now removed(thanks to the way the .use method works in nodejs), and the file path becomes ../proj_dir/public/style.css

2 Likes

app.use([path,] callback [, callback...])

Since path defaults to “/”, middleware mounted without a path will be executed for every request to the app.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.