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

前端之家收集整理的这篇文章主要介绍了node.js – 如何获取请求的字节大小?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在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’](但有些客户端可能不会发送此标头).

原文链接:https://www.f2er.com/nodejs/241290.html

猜你在找的Node.js相关文章