An introduction to case

Type http://localhost:8080/index.html to open a page in your browser. The index.html page is located in assets on the server.

const path = require("path");

const express = require("express");

const app = express();

app.use(express.static(path.join(__dirname, "assets")));

app.listen(8080.'localhost'.function() {
  console.log('server is running on 8080');
});
Copy the code

Question: Since you are accessing the index.html file in assets directory. But why isn’t access http://localhost:8080/assets/index.html, http://localhost:8080/index.html. This refers to express.static.

How express.static works

In the official Express documentation, it is explicitly stated that Express. static is a middleware function. It serves static files and is based on serve-static.

exports.static = require('serve-static');
Copy the code

For details on how to use Express. static, see serve-static middleware. Static (path.join(__dirname, “assets”)) app.use(express.static(path.join(__dirname, “assets”))) Any route is first treated as an access to a static resource. If the URL path matches a file in assets, the resource is returned. If none matches, the request is considered a dynamic resource request. Walk by table logic. Therefore, any request from the client to the server is first seen as a static resource request, and when no matching static resource file is found, the request is considered as a dynamic resource request. Dynamic resource requests walk by logic.

Set up multiple static resource directories

What if there is more than one static resource directory? Specify a few more directories as static resource directories.

app.use(express.static(path.join(__dirname, "assets")));
app.use(express.static(path.join(__dirname, "public")));
Copy the code

When enter http://localhost:8080/index.html in your browser, the first to assets directory to find index. The HTML file, if found, return directly, not to perform. If not, go to the public directory. Summary: The priority of a static resource directory is positively related to the location it defines.

The virtual path

Resource requests to servers can be divided into static resource requests and dynamic resource requests. When a user enter http://localhost:8080/users in your browser, literally is a static resource request or unable to distinguish between the dynamic resource request. It might be a get request to the information of all users method, it can also be a static resource request for http://localhost:8080/users.html. To make this distinction literal, you can prefix all static resource requests with a prefix such as /static. Static is a virtual path that only exists at the logical level, not the physical level. Therefore, when visiting http://localhost:8080/static/users, a see will know this is a static resource request.