过滤node.js中的传出请求以进行日志记录

Kos*_*aur 5 javascript node.js

我正在构建一个Express应用程序,在某些请求中必须进行自己的HTTP调用.我可以使用Superagent,request或node自己的http.request.事实是,我需要记录所有这些服务器发起请求及其各自的响应.log.info在每一个之前打电话似乎很傻.

如何为所有传出的HTTP调用添加预过滤器,理想情况下访问两者reqres

注意:我对记录进入我正在构建的服务器的请求不感兴趣,只是在服务器本身启动的请求中.将我的服务器视为另一个黑匣子服务器的客户端.

Tri*_*eur 2

您可以做的是修补 http 和 https 并代理该request方法。这样您就可以拥有一个全局处理程序来捕获 req 和 res 对象。

var http    = require('http');
var https   = require('https');

var patch = function(object) {
    var original = object.request;

    // We proxy the request method
    object.request = function(options, callback) {
        // And we also proxy the callback to get res
        var newCallback = function() {
            var res = arguments[0];

            // You can log res here
            console.log("RES",res.statusCode);

            callback.apply(this,arguments);
        }

        var req = original(options, newCallback);

        // You can log your req object here.
        console.log(req.method,req.path);

        return req;
    }
}

patch(http);
patch(https);

http.get("http://www.google.com/index.html", function(res) {
  console.log("Got response");
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});
Run Code Online (Sandbox Code Playgroud)

编辑:如果您request也使用 npm 包,这可能会起作用,因为它可能只是依赖于内置的 node.jshttp.request方法。