* Expanded the solution for the 'Get Route Parameter Input from the Client' challenge * Expanded the guide for the 'Use body-parser to Parse POST Requests' challenge * Rewritten guide for the 'Serve JSON on a Specific Route' challenge and fixed source link * Expanded the guide for the 'Serve Static Assets' challenge * Expanded solution to the 'Get Query Parameter Input from the Client' challenge and fixed links to source file * Added solution to the 'Chain Middleware to Create a Time Server' challenge and fixed link to source file * Rewrite the 'Start a Working Express Server' challenge * Expanded the guide for 'Expand Your Project with External Packages from npm' * Added reference to semantic versioning in 'Add a Version to Your package.json' * fix/remove-links+fix-solutions * fix/remove-more-links
1.2 KiB
title
title |
---|
Serve Static Assets |
Serve Static Assets
Serving static webpages and assets is fairly simple with express
. This could be useful for building your own portfolio website or blog, single-page web applications etc.
To serve static assets from the public
folder in the you can use the express.static()
method as the middleware. This method takes the endpoint and the absolute path to the directory containing the static assets as arguments and exposes the files in that folder at the given endpoint. By default, if the endpoint is not passed to the method, the folder is exposed at the root endpoint i.e. /
for the application.
The __dirname
variable is a string containing the absolute path to the root of your project which has to be concatenated with the folder containing the assets.
Add the following line to your file above all defined routes to achieve the desired result:
// Normal usage
app.use(express.static(__dirname + "/public"));
// Assets at the /assets route
app.use("/assets", express.static(__dirname + "/public"));