Digging Into Node.js

Serving Static Files with Express

Kyle Simpson

Kyle Simpson

You Don't Know JS
Digging Into Node.js

Check out a free preview of the full Digging Into Node.js course

The "Serving Static Files with Express" Lesson is part of the full, Digging Into Node.js course featured in this preview video. Here's what you'd learn in this lesson:

Kyle configures Express to handle requests for static files with the app.use method, adding a custom header and utilizing the Express static server.

Preview
Close

Transcript from the "Serving Static Files with Express" Lesson

[00:00:00]
>> Kyle Simpson: Now we also want to send out, that we wanna route for handling any of the static file requests. And so we're gonna call app.use, that's the more general form of the middleware. When we say app.get, it's specifically for get requests. App.use is for all incoming requests. And we're gonna call express.static.

[00:00:33]
>> Kyle Simpson: And we're gonna configure express.static with our WEB_PATH as the route. I mean, as the doc root.
>> Kyle Simpson: And then there's some additional configurations that we can optionally put in there, like we can put in.
>> Kyle Simpson: These that I've got here in the solution file. Not that these are strictly necessary, but we can put those in if we'd like.

[00:01:13]
>> Kyle Simpson: This function here is called whenever we have an outbound request and we need to add custom headers. So this is how you add custom headers with Express. You have to specify this setHeaders function and then do your own setHeaders. So here I wanted to make sure to pass in the server response.

[00:01:30]
That's something that static alias was handling for us before. We want it to do that with this. So basically express.static is a static file server that's almost exactly identical to node static. It's the one that express shapes, but it's almost identical. It's gonna handle almost all the stuff that we would think of.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now