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

我在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或者你可以使用request-stats模块。

 var requestStats = require('request-stats'); var stats = requestStats(server); stats.on('complete', function (details) { var size = details.req.bytes; }); 

细节对象如下所示:

 { 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'] (但有些客户端可能不会发送这个头文件)。