如何在Node.js中捕获原始请求

How to capture a raw request in Node.js

本文关键字:原始 请求 js Node      更新时间:2023-09-26

我能够在Node.js中使用下面的源代码捕获原始请求。

var http = require('http');
var express = require('express');
var remote = express();
remote.use(function(req, res, next) {
  req.socket.once('data', function(data) {
    console.log(data.toString());
  });
  next();
});
remote.use(function(req, res, next) {
  res.end('end');
});
http.createServer(remote).listen(8080);

但是这个源可以在(包括)第二个请求之后捕获原始请求,因为第一个请求是在绑定事件处理程序之前被消耗的。如果客户端不使用keep alive,我将无法捕获任何请求。

如何捕获原始请求,包括第一个请求?

我找到了一种方法在http.Server上使用'connection'事件。

var http = require('http');
var express = require('express');
var remote = express();
remote.use(function(req, res, next) {
  res.end('end');
});
var server = http.createServer(remote);
server.on('connection', function(socket) {
  socket.on('data', function(chunk) {
    console.log(chunk.toString());
  });
});
server.listen(8080);

嘿,不确定你是否还有问题。我最近不得不解决这个问题,我尝试了很多东西,这就是我最终的结果:

https://github.com/vincenzorm117/http-capture/blob/master/index.js

下面是代码,以防链接有任何问题:

var PORT = process.env.PORT || 3000
const net = require('net')
const fs = require('fs')
if( !fs.existsSync('./payloads') ) {
    fs.mkdirSync('./payloads');
}
var server = net.createServer((sock) => {
    console.log(`Connected: ${sock.remoteAddress}`)
    let filename = FileName(sock);
    let wstream = fs.createWriteStream(`./payloads/${filename}`);

    sock.on('data', wstream.write.bind(wstream));
    sock.on('end', () => {
        wstream.end();
        delete wstream;
        console.log(`Disconnected: ${sock.remoteAddress}`)
    });
    setTimeout(() => {
        if( !sock.destroyed ) {
            sock.write('HTTP/1.1 200 OK'r'n');
            sock.end();
        }
    }, 3000);
});
server.listen(PORT, 'localhost');

function FileName() {
    var d = new Date(),
    year = d.getFullYear(),
    month = d.getMonth(),
    date = d.getDate();
    hour = d.getHours();
    minutes = d.getMinutes();
    seconds = d.getSeconds();
    if( month < 10 ) month = '0' + month;
    if( date < 10 ) date = '0' + date;
    if( hour < 10 ) hour = '0' + hour;
    if( minutes < 10 ) minutes = '0' + minutes;
    if( seconds < 10 ) seconds = '0' + seconds;
    return `request__${year}-${month}-${date}__${hour}-${minutes}-${seconds}.http`;
}



我有点懒,设置服务器在3秒后终止连接,而不是解析HTTP请求。你可以把它更新为1秒,应该没问题。