我的目标是
当用户进入特定页面时将消息打印到我的控制台上
无需编写.html扩展名即可访问页面。
如果我使用以下内容(其中test.html不是现有页面),我将看到
用户尝试访问/test
或/test.html
页面时在控制台中显示的预期消息。
router.get(/^\/test(\.html)?$/, async (req, res) => {
console.log('User trying to access test.html page')
res.send('welcome to test page')
})
但是如果我对现有页面(/dashboard.html
)进行同样操作
router.get(/^\/dashboard(\.html)?$/, async (req, res) => {
console.log('User trying to access dashboard.html page')
res.send('welcome to dashboard page')
})
当用户尝试访问/dashboard
时,我会在控制台中看到预期的消息,但是当他尝试访问/dashboard.html
时,页面将仅加载而在控制台中看不到任何消息。
为什么会这样?
答案 0 :(得分:1)
我认为问题在于,您告诉应用程序使用静态文件,然后才告诉应用程序使用路由器。
我的意思是,如果您这样做(假设我们在公用文件夹中有dashboard.html文件):
const express = require("express");
const app = express();
const router = express.Router();
const port = 3000;
router.get(/^\/test(\.html)?$/, async (req, res) => {
console.log("User trying to access test.html page");
res.send("welcome to test page");
});
router.get(/^\/dashboard(\.html)?$/, async (req, res) => {
console.log("User trying to access dashboard.html page");
res.send("welcome to dashboard page");
});
app.use("/", router);
app.use(express.static("public"));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
它应该可以按预期工作。
但是,似乎您将app.use(express.static ...)放在了app.use路由器之前。像这样:
const express = require("express");
const app = express();
const router = express.Router();
const port = 3000;
app.use(express.static("public"));
router.get(/^\/test(\.html)?$/, async (req, res) => {
console.log("User trying to access test.html page");
res.send("welcome to test page");
});
router.get(/^\/dashboard(\.html)?$/, async (req, res) => {
console.log("User trying to access dashboard.html page");
res.send("welcome to dashboard page");
});
app.use("/", router);
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
因此,在这种情况下,当您键入dashboard.html的确切路径时,它将不会使用路由器来解析内容,而只会从公用文件夹中获取内容。
代码中app.uses(...)只是顺序问题