Serving Static files in Express framework

There are several ways to serve static files in Express.

Photo by Florian Olivo on Unsplash

built-in function: static

The Function is like this:

express.static(root, [options])

The root argument specifies the directory from the server.

For example, if you want to let your homepage folder be one of the routes, you can use app.use(express.static(‘homepage’)); Thus, you can access your homepage file using the URL below: http://localhost:3000/homepage.html.

Ordering:

App.use(express.static(‘homepage’));

App.use(express.static(‘customer’));

Express will show the file under the homepage folder first.

Path prefix:

App.use(‘/static’, express.static(‘homepage))

The URL will be http://localhost:3000/static/homepage.html

File directory issue: wrong directory

App.use(‘/static’, express.static(path.join(_dirname, ‘homepage’)))

Java Full stack developer | Google Android Associate developer certified | CompTIA Linux + certified | Teaching Assistant | https://www.linkedin.com/in/yucheliu