Home >Web Front-end >JS Tutorial >How to host static files with Express

How to host static files with Express

php中世界最好的语言
php中世界最好的语言Original
2018-06-04 09:45:381587browse

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 can help us host static files, js, css, img, etc.

express.static use

#Basic 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.

Add

var express = require('express');
var app = express();
app.use(express.static('public'));
in app.js and we can pass

http://localhost:3000/css/style.css

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 the

attributes of the resources at a glance.

var express = require('express');
var app = express();
app.use('static',express.static('public'));
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn