我正在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’](但有些客户端可能不会发送此标头).