Serving Files

At its core, HTTP is a file transfer protocol.

node-static

In earlier lessons, you may have used the node-static package to serve your HTML, JS, CSS, images, etc...

node-static is a standalone static file server built in NodeJS

It's useful for local development but not great for production deployments

Usage:

$ npm install node-static
$ npx node-static
npx: installed 6 in 1.359s
serving "." at http://127.0.0.1:8080

static file server in Express

LAB: static file server

oops

The good news: your web server can now serve static files to its clients!

The bad news: your web clients can now see any files they like in your project

(including your server source code and configuration files, which may include secrets like passwords)

LAB: Hack Your Own Server

open a web browser and visit http://localhost:5000/package.json

package.json should probably be more secret than that :-)

Solution: public directory

To keep server-side code and configuration files secret, most web apps have a public directory containing static files

This is one major difference between static sites and web apps -- since some of your code runs on your server, and some runs on your client's browser, your project directory structure needs to segregate client-side files from server-side files

Now you can put HTML, CSS, PNG, and .js files inside /public where your clients can fetch them as needed

Note that the URL path /index.html maps directly to the filesystem path static-server/public/index.html

index.html

A little historical note...

Now open a web browser and visit http://localhost:5000/ and you will see the contents of index.html ("Hello in HTML") even though your request did not contain the words "index" or "html", just the path /

Content-Type

Viewing Headers

TIP: open the browser DevTools and click on the Headers sub-tab to see Content-Type and other headers:

headers

404 Not Found and other status codes

open a web browser and visit http://localhost:5000/oops.html

if there is an error loading the file (in this case, there is simply no file by that name),

the server must send the correct status code

Note: even though there is an error, the server still returns a body and content-type for display to the user.

In this case, we just see Express' boring default error page, but it's possible to get very creative with web site error pages.

 Previous Lesson Next Lesson 

Outline

[menu]

/