【问题标题】:Not able to receive empty get request with express static in nodejs无法在nodejs中接收带有express static的空get请求
【发布时间】:2015-12-18 11:56:32
【问题描述】:

我正在尝试使用 express static 获取网页,下面是服务器代码。

app.use(express.static('DIR/webfiles'));
app.get('/test', function(req, res) {
    console.log("got req");
    res.sendfile("login.html");
});

app.get('/', function(req, res) {
    console.log("got req");
    res.sendfile("login.html");
});

当我请求 localhost:port/test (从浏览器)时,我可以看到 login.html 页面并在服务器端打印“got req”,但是当我请求 localhost:port 或 localhost:port/ 时,我在 webfiles 文件夹中获取了一些其他文件。它不打印“得到请求”。空 GET 处理程序是否被 express static 覆盖?

当我删除“app.use(express.static('DIR/webfiles'));”时行,它能够获得空的 GET 请求,但不能按我想要的方式工作。为什么它没有收到空请求以及如何处理空请求。

【问题讨论】:

  • 据我所知localhost:port 请求默认自动将/ 添加到您的请求中,然后变为localhost:port/。所以实际上你应该得到login页面而不是其他文件。
  • localhost:port/ 也给出相同的结果
  • 尝试使用节点核心模块path = require ('path'),然后在您的目录中使用__dirnamepath.join()。这将确保您点击静态目标目录。

标签: node.js express get


【解决方案1】:

Express 将按声明顺序处理各种路由处理程序(包括静态中间件)。

如果你请求/,静态中间件会检查一个名为webfiles/index.html的文件,如果存在则返回。

要覆盖此行为,请确保在静态中间件声明之前声明自己的路由处理程序

// This will match requests to `/` and since it's declared before
// the static middleware, it will get to handle those requests.
app.get('/', function(req, res) {
  console.log("got req");
  res.sendfile("login.html");
});

app.use(express.static('DIR/webfiles'));

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 2020-05-31
    • 2018-08-25
    • 2021-12-25
    • 2020-06-25
    • 1970-01-01
    • 2019-06-26
    • 2019-03-01
    • 2018-01-06
    相关资源
    最近更新 更多