In your code, you have two route handlers that can send responses back to incoming requests.
This one:
app.get("/", (req, res) => {
res.sendFile("index.html", {root: "public"});
});
is pretty obvious. If the request is /
, then send back the index.html
file.
This one:
app.use(express.static("public"));
tells express to compare the incoming path of the request to any files in your public directory and, if they match, then send that file back as the response to that request. This is exactly what express.static()
is designed for and what it is supposed to do. It is commonly used for serving static resources such as CSS files, JS files and even static HTML files since one route can automatically serve an entire directory hierarchy.
So, if an incoming request arrives for /game/game.html
and, the public directory contains this:
public
game
game.html
Then, express.static("public")
will find a match for /game/game.html
and will send back the game.html
file as the response. This is working as designed.
Because of this, you should never put anything that you don't want automatically served inside the directory that you pass to express.static()
- in your specific code example, the "public" directory.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…