【问题标题】:How does fallthrough work with express.static()?fallthrough 如何与 express.static() 一起工作?
【发布时间】: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 文件并应该呈现它,但它会调用 nextget 处理程序关于被执行。为什么?

我不太清楚如何提供静态资产,我想当我转到 /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.htmlabout.html,而不是index.html

标签: javascript node.js express


【解决方案1】:

来自express.static() 文档https://expressjs.com/en/4x/api.html#express.static

该函数通过将 req.url 与提供的根目录组合来确定要服务的文件。

(可选)它还会查找目录索引文件 - 请参阅index 选项。

所以在你的场景中:

  • / 将匹配您根目录中的 index.html 文件。
  • /about 将尝试匹配名为about 的文件,或./about 子目录中的index.html 文件。如果没有这样的匹配,那么请求将被传递到下一个 middelware。

【讨论】:

    【解决方案2】:

    root 参数指定提供静态资产的根目录。该函数通过将 req.url 与提供的根目录组合来确定要服务的文件。

    所以,app.use(express.static(path.join(__dirname, "public"))) 服务于public 目录。

    访问/路线

    请记住,要提供的文件将通过将req.url 与root 组合来确定。所以,在这种情况下,req.url/,root 是 public。所以 express 会尝试服务public/index.html,如果没有明确指定文件,index.html 是默认值。

    发送指定的目录索引文件。设置为 false 以禁用目录索引。

    这个文件会被找到并被渲染,请求在那里结束,所以/的get handler不会被执行。

    您可以将index属性设置为false,然后express默认不会查找index.html文件。

    因此,设置app.use(express.static(path.join(__dirname, "public"), { index: false })) 将使express 默认不查找index.html 文件,现在如果您访问/ 路由,将执行/get 处理程序。

    访问/about路线

    这次req.url/about,所以express 将尝试服务public/about/index.html,但找不到它,因此它调用next() 并执行/about 的get 处理程序。

    访问/about.html路线

    这次req.url/about.html,所以express 将尝试提供public/about.html,如果找到将呈现,否则将调用next()

    【讨论】:

      猜你喜欢
      • 2018-01-13
      • 2021-04-05
      • 2023-02-02
      • 1970-01-01
      • 2017-08-09
      • 2011-10-13
      • 2015-06-07
      • 2018-07-13
      • 2012-06-22
      相关资源
      最近更新 更多