Express.js 正确文件未作为响应发送

问题描述 投票:0回答:2

我知道这会是一些愚蠢的事情,但我不知道为什么 express.js 会这样做。 所以,我在

GET
请求中发送一个 HTML 文件

const express = require("express");
require('dotenv').config()

const app = express();
const PORT = process.env.PORT || 5000;

app.use(express.static(__dirname + "/public"));

app.get("/", (req, res) => {
  // console.log("Hello");
  // res.sendFile(__dirname + "/public/index2.html");
})

app.listen(PORT, () => {
  console.log("Server started on port: " + PORT)
})

现在我正在发送

index.html
而不是
index2.html
但它仍然发送
index.html
文件,即使是
console.log
也没有被打印。
有人可以告诉我为什么会这样吗?

javascript node.js express file-sharing
2个回答
1
投票

这是因为您启用了为整个应用程序提供静态文件服务。这意味着 expess 将首先从公用文件夹路由文件,你有

index.html
对应于
/
.

你可以为静态的东西设置一个特定的路径:

app.use('/static', express.static(__dirname + '/public'));

更多信息在这里:https://expressjs.com/en/starter/static-files.html


0
投票

Express一次测试一条路线按顺序直到一个匹配。

app.use(express.static(__dirname + "/public"));

您的第一条路线,即静态路线,匹配!


如果您想将显式端点优先于静态端点,则将静态路由放在最后

© www.soinside.com 2019 - 2024. All rights reserved.