- MERN Quick Start Guide
- Eddy Wilson Iriarte Koroliova
- 353字
- 2021-06-25 21:30:17
There's more...
Let's pretend that you have a big project that serves dozens of static files, including images, font files, and PDF documents (those about privacy and legal stuff) among others. You decided that you want to keep them in separate files, but you do not want to change the mount path or URI. They can be served under /public, for example, but they will exist in separate directories in your project directory:
First, let's create the first public directory that will contain a single file named index.html:
- Create a new directory named public if you didn't create it in the previous recipe
- Move into the new public directory
- Create a new file named index.html
- Add the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Simple Web Application</title> </head> <body> <section role="application"> <h1>Welcome Home!</h1> </section> </body> </html>
- Save the file
Now, let's create a second public directory that will contain another file named second.html:
- Move back out of the public directory
- Create a new directory named another-public
- Move into the new another-public directory
- Create a new empty file named second.html
- Add the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Simple Web Application</title> </head> <body> <section role="application"> Welcome to Second Page! </section> </body> </html>
- Save the file
As you can see, both files exist in different directories. To serve those files under one mount point:
- Move back out of the another-public directory
- Create a new file named router-serve-static.js
- Include the ExpressJS and path libraries. Then, initialize a new ExpressJS application:
const express = require('express') const path = require('path') const app = express()
- Define a router:
const staticRouter = express.Router()
- Use the express.static configurable middleware function to include both directories, public and another-public:
const assets = { first: path.join(__dirname, './public'), second: path.join(__dirname, './another-public') } staticRouter .use(express.static(assets.first)) .use(express.static(assets.second))
- Mount the Router to the "/" path:
app.use('/', staticRouter)
- Listen on port 1337 for new connections:
app.listen( 1337, () => console.log('Web Server running on port 1337'), )
- Save the file
- Open a terminal and run:
node router-serve-static.js
- To see the result, in the browser, navigate to:
http://localhost:1337/index.html http://localhost:1337/second.html
- Two different files in different locations were served under one path
If two or more files with the same name exist under different directories, only the first one found will be displayed on the client-side.