Node.js 如何获取请求的字节大小?

Node.js 如何获取请求的字节大小?,node.js,express,Node.js,Express,我正在Node.js Express中制作一个API,它可能会收到大量请求我真的很想看看请求有多大。 //.... router.post('/apiendpoint', function(req, res, next) { console.log("The size of incoming request in bytes is"); console.log(req.????????????); //How to get this? }); //.... 您可以使用req.socke

我正在Node.js Express中制作一个API,它可能会收到大量请求我真的很想看看请求有多大。

//....
router.post('/apiendpoint', function(req, res, next) {
  console.log("The size of incoming request in bytes is");
  console.log(req.????????????); //How to get this?
});
//....

您可以使用
req.socket.bytesRead
或使用模块

详细信息对象如下所示:

{
    ok: true,           // `true` if the connection was closed correctly and `false` otherwise 
    time: 0,            // The milliseconds it took to serve the request 
    req: {
        bytes: 0,         // Number of bytes sent by the client 
        headers: { ... }, // The headers sent by the client 
        method: 'POST',   // The HTTP method used by the client 
        path: '...'       // The path part of the request URL 
    },
    res  : {
        bytes: 0,         // Number of bytes sent back to the client 
        headers: { ... }, // The headers sent back to the client 
        status: 200       // The HTTP status code returned to the client 
    }
}
因此,您可以从
details.req.bytes
获取请求大小


另一个选项是
req.headers['content-length']
(但一些客户端可能不会发送此标题)。

五年后,这是谷歌针对此问题的第一个链接


但这里不需要npm模块。和
req.socket.bytesRead
number也不能使用,因为套接字读取的每个字节都会被计数,甚至HTTP头也是如此。更糟糕的是,对于同一套接字,next请求继续增加该值

最好的方法是为每个数据块使用一个简单的计数器:

// Set up the byte counter
let byteCount = 0

// Listen the chunk events
req.on('data', (chunk) => {
    // Increment the byte counter
    byteCount += Buffer.from(chunk).length
    // Check the body byte length
    if(byteCount > REQ_BYTE_MAX) {
        // Return an error to the client
        res.writeHead(413, { 'Content-Type': 'text/plain' })
        res.end('Request content is larger than the limit.')
    }
})

您不能使用
req.socket.bytesRead
,因为
socket
是可重用的,所以
bytesRead
是通过给定
socket
传递的总流量的大小,而不是特定请求的大小。
我使用的一个快速解决方案-一个小型中间件(我使用Express):


然后你可以在你的中间件中使用
req.socketProgress

是否
req.headers['content-length']
足够好?太棒了,这似乎足够了非常好的概述。如果您还添加
req.headers['content-length']
我可以接受:)好的,但请注意我的注释:)套接字字节读取似乎不起作用(通常给出太大的值),我想这是因为节点的套接字池。虽然请求统计工作得很好,但为什么details.req.bytes总是为零(0),即使我发送请求正文或查询参数也是如此。我需要知道请求的整个大小,包括头
req.socket.bytesRead
给出的是一个累积值,而不是当前请求的值。
// Set up the byte counter
let byteCount = 0

// Listen the chunk events
req.on('data', (chunk) => {
    // Increment the byte counter
    byteCount += Buffer.from(chunk).length
    // Check the body byte length
    if(byteCount > REQ_BYTE_MAX) {
        // Return an error to the client
        res.writeHead(413, { 'Content-Type': 'text/plain' })
        res.end('Request content is larger than the limit.')
    }
})
const socketBytes = new Map();
app.use((req, res, next) => {
    req.socketProgress = getSocketProgress(req.socket);
    next();
});

/**
 * return kb read delta for given socket
 */
function getSocketProgress(socket) {
    const currBytesRead = socket.bytesRead;
    let prevBytesRead;
    if (!socketBytes.has(socket)) {
        prevBytesRead = 0;
    } else {
        prevBytesRead = socketBytes.get(socket).prevBytesRead;
    }
    socketBytes.set(socket, {prevBytesRead: currBytesRead})
    return (currBytesRead-prevBytesRead)/1024;
}