This time I will show you how to use Express to host static files, and what are the precautions for using Express to host static files. The following is a practical case, let's take a look.
Middlewareexpress.static
When we use express to initialize a directory, it will be in app.js I saw a lot of recommended app.use. One of the main middlewares is express.static (middleware still retained in version 4.0)var express = require('express'); var app = express(); app.use('/static',express.static('public'));
express.static use
There is css under public in the project directory , js, img and other folders. I really need to host them through express so that we can access the data when we start the server. Addvar express = require('express'); var app = express(); app.use(express.static('public'));
http://localhost :3000/js/style.js
http://localhost:3000/img/style.png
Note:The paths of all files are relative to the storage directory. Therefore, the directory name where the static files are stored will not appear in the URL.
Virtual directory
This is achieved by specifying a mounting path for the static resource directory. We can add a virtual directory to our static files, which sometimes makes it easier for us to manage our URLs in a unified manner, and also see theattributes of the resources at a glance.
var express = require('express'); var app = express(); app.use('static',express.static('public'));
How to operate Vue to remove the # sign in the path
How to use vue to click on the blank space Hidden div implementation
The above is the detailed content of How to host static files with Express. For more information, please follow other related articles on the PHP Chinese website!