【发布时间】:2021-04-17 18:35:14
【问题描述】:
所以,我有一个基本的快速设置,如下所示:
const path = require("path");
const express = require("express");
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.get("/", (req, res) => {
res.send("Home Page");
});
app.get("/about", (req, res) => {
res.send("About Page");
});
app.listen(3000, () => {
console.log("Server listening on PORT 3000");
});
在上面的代码中,app.use() 中间件将为每个请求执行,因为app.use() 的默认路径是/。
现在express.static() 将服务于public 目录,所以如果我转到/ 路径,我将看到index.html 文件的内容,而app.get("/") 中间件将不会被执行。
但是当我转到/about 时,我看到了从app.get("/about") 发送的内容。这是我不明白的,因为根据文档,它仅在找不到文件时才调用next(),但当找到文件时,请求就会停止。
所以,当我导航到 /about 时,app.use() 将是第一个被执行的,它会找到 index.html 文件并应该呈现它,但它会调用 next 和 get 处理程序关于被执行。为什么?
我不太清楚如何提供静态资产,我想当我转到 /about 时,它实际上并不是在寻找 index.html 文件,而是它在寻找什么文件?
【问题讨论】:
-
我认为here 是您问题的答案
-
重点在这里:
So, when I navigate to /about, app.use() will be the first to get executed and it will find index.html。它将找到/about/index.html或about.html,而不是index.html。
标签: javascript node.js express