【问题标题】:nodejs express router doesn't catch get request to /mypage.htmlnodejs express 路由器没有捕获到 /mypage.html 的获取请求
【发布时间】:2020-03-12 23:27:48
【问题描述】:

我的目标是

  1. 当用户进入特定页面时向我的控制台打印一条消息

  2. 无需编写 .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 时,页面只会加载而在我的控制台中看不到任何消息。 为什么会这样?

【问题讨论】:

  • 添加设置快速服务器的代码。在这个路由器之前。
  • 我已经这样做了。这些路线在src/routers/user.js 底部我使用module.exports = router 然后在src/index.js 我包括const userRouter = require('./routers/user') 然后app.use(userRouter)
  • 我在你的帖子中看不到

标签: node.js express routing url-routing


【解决方案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(...)的顺序问题

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2016-07-09
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多