2015-08-30 23 views
5

Sto facendo un'API in Node.js Express che potrebbe richiedere grandi richieste. Mi piacerebbe davvero vedere quanto è grande la richiesta.Come ottenere la dimensione in byte della richiesta?

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

'req.headers ['content-length']' abbastanza buono? – robertklep

+0

Impressionante, sembra essere davvero abbastanza – Automatico

risposta

8

È possibile utilizzare req.socket.bytesRead oppure è possibile utilizzare il modulo request-stats.

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

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

I dettagli oggetto simile a questo:

{ 
    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 
    } 
} 

in modo da poter ottenere la dimensione richiesta details.req.bytes.

Un'altra opzione è req.headers['content-length'] (ma alcuni client potrebbero non inviare questa intestazione).

+0

Panoramica molto bella. Se si aggiungono anche 'req.headers ['content-length']' Posso accettare :) – Automatico

+1

Ok, ma sii consapevole della mia annotazione :) –

+0

Socket bytesRead non sembra funzionare (di solito dà valori troppo grandi), I supponiamo che sia dovuto al pooling di socket del nodo. Tuttavia, le statistiche di richiesta funzionano bene. –

Problemi correlati