Backend development with Express
  • Welcome!
  • Intro to backend development with Express
    • Tutorial
      • Getting started
      • Step 1: Setting up your project
      • Step 2: Installing Express
      • Step 3: Building the server
      • Step 4: Communicating with the server
      • Step 5: Routing
      • Step 6: Serving static files
      • Step 7: Sending your blog post to your server
      • Step 8: Extracting the blog post
      • Step 9: Saving your blog post
      • Step 10: Displaying your blog posts
      • Congratulations!
    • Extras
      • More ideas
      • Individual Blog Posts
    • Keywords
    • Command-line cheatsheet
Powered by GitBook
On this page
  1. Intro to backend development with Express
  2. Tutorial

Step 6: Serving static files

PreviousStep 5: RoutingNextStep 7: Sending your blog post to your server

Last updated 6 years ago

So we know how to send back a simple message. But what if you want to send back a whole HTML page, or an image?

Things like HTML files, images etc are known as static assets. If you want your server to "serve" static assets back to the browser, you need to do something different than just using the res.send() method.

To be able to send any file from the server we need a special, built-in middleware function that comes with Express: express.static(). Read more about it .

Say we want to serve all the static assets in our public folder. The express.static() function will look like this:

server.js
app.use(express.static("public"));

Serve static files from your server

Delete all your app.get endpoint functions, and replace them with the line of code above. Restart your server, refresh your browser and see what happens! If you see a Node Girls CMS, then your static assets have been successfully served.

here