【问题标题】:Capture all http requests with node/express使用 node/express 捕获所有 http 请求
【发布时间】:2017-01-02 01:25:09
【问题描述】:

我希望从我的网站上的任何请求(图像、字体、css、js 等)中捕获所有数据,以便我可以捕获文件详细信息,特别是文件名和文件大小。我发现了几乎相同的问题/解决方案:

Node.js : How to do something on all HTTP requests in Express?

但 Express v4 似乎已弃用该解决方案。有没有一个简单的解决方案来做到这一点?作为另一种方法,我尝试了以下解决方案,但没有成功:

var express = require("express");
var path = require("path");
var port = process.env.PORT || 3000;

var app = express();
var publicPath = path.resolve(__dirname, "public");

app.use(express.static(publicPath));

app.get("/", function(req, res){
    // I want to listen to all requests coming from index.html
    res.send("index.html");
});

app.all("*", function(){
    // can't get requests
})

app.listen(port, function(){
    console.log(`server listening on port ${port}`);
});

另外,我不希望 Fiddler/Charles 这样做,因为我希望在我的网站上显示这些数据。

【问题讨论】:

  • 记录请求路径和Content-Length 标头是否足够?
  • 嘿@robertklep,可能我对这方面不太精通,所以它可以让我获取文件名和重量,我认为这就足够了。
  • 在这种情况下,使用morgan's tiny logger 可能就足够了。

标签: node.js express


【解决方案1】:

快速路线基于顺序。请注意,您在问题中链接的答案定义了中间件,并在所有其他路由之前使用了

其次,您尝试实现一些需要中间件的东西,而不是通配符路由。根据他们的docs,您在问题中提供的链接中的模式并未被弃用。

app.use(function (req, res, next) {
  // do something with the request
  req.foo = 'testing'
  next(); // MUST call this or the routes will not be hit
});

app.get('/', function(req, res){
    if (req.foo === 'testing') {
      console.log('works');
    }

    res.send("index.html");
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    相关资源
    最近更新 更多