Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

express - Why is node.js sending the entire public folder, When only root index.html specified?

So I am making a node.js server for my webpage. And after having added root route that sends the index.html it also sends the game.html page with out it being specified. The game.html file is in a folder called game in the root directory. So I am wondering why is it sending the game.html file? And is it supposed to happened, with out me saying what the server is supposed to send in the "/game" path?

I am using Node.js and Express.

const express = require("express");
const app = express();
const port = 3000;

app.use(express.static("public"));

// ROUTES
app.get("/", (req, res) => {
    res.sendFile("index.html", {root: "public"});
})

// Listening
app.listen(port, () => {
    console.log(`Listening at port http://localhost:${port}`);
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...