如何获得请求的字节大小? [英] How to get byte size of request?

查看:325
本文介绍了如何获得请求的字节大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making an API in Node.js Express which might get large requests coming in. I would really like to see how big the request are.

//....
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,也可以使用请求统计模块.

You can use req.socket.bytesRead or you can use the request-stats module.

var requestStats = require('request-stats');
var stats = requestStats(server);

stats.on('complete', function (details) {
    var size = details.req.bytes;
});

Details对象看起来像这样:

The details object looks like this:

{
    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获取请求大小.

So you can get the request size from details.req.bytes.

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

Another option is req.headers['content-length'] (but some clients might not send this header).

这篇关于如何获得请求的字节大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆