简体   繁体   中英

Why does omitting the line app.use(express.static(__dirname, 'public')) stop my html pages from loading css files?

I'm learning to use NodeJS and Express and just used "express" to generate the scaffolding for a project. I don't understand the purpose of:

app.use(express.static(path.join(__dirname, 'public')));

My understanding of app.use() is that it loads functions as middleware, so app.use(express.static(path.join(__dirname, 'public'))) must be loading a function, right? Is this function loading paths to some files that I'm declaring as static?

In my layout.jade file, I have this line in the head:

link(rel='stylesheet', href='/stylesheets/style.css')

How does my app know to begin the href link with a '/public' (if that's what it's doing) when I set the app.use(express.static) line? Because when I get rid of the app.use(express.static) line, it gives a 404 to finding the css file, even when I change the href to '/public/stylesheets/style.css'.

And how does it know that I'm trying to access that static file at all? What if I had a file called 'root/stylesheets/style.css' as well as the 'root/public/stylesheets/style.css'?

Right, app.use() loads a function to be used as middleware. In this context, it loads the result of express.static(path.join(__dirname, 'public')) .

The result of express.static(path.join(__dirname, 'public')) is a function (in JavaScript, functions may return functions), a function that express understands as a middleware (ie it has the following signature: function(request, response, next) {

express.static() is a function that takes a path, and returns a middleware that serves all files in that path to / . (If you wanted to prefix it with /public or whatever, you'd write app.use('/public', express.static(path.join(__dirname, 'public'))) , where the first /public is the web path and the second is the filesystem path of the files being served).


For better clarity, the following:

app.use('/a', express.static(path.join(__dirname, 'b')));

would serve all files inside of the b directory, and have them accessible through http://example.com/a/FILE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM