我正在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?
});
//....
Run Code Online (Sandbox Code Playgroud)
Ale*_*ler 15
您可以使用req.socket.bytesRead
或者您可以使用request-stats模块.
var requestStats = require('request-stats');
var stats = requestStats(server);
stats.on('complete', function (details) {
var size = details.req.bytes;
});
Run Code Online (Sandbox Code Playgroud)
详细信息对象如下所示:
{
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
}
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以从中获取请求大小details.req.bytes
.
另一种选择是req.headers['content-length']
(但有些客户端可能不会发送此标头).
您不能使用,req.socket.bytesRead
因为socket
它是可重用的,因此bytesRead
是给定的总流量大小socket
,而不是特定请求的大小。
我使用的一个快速解决方案 - 一个小型中间件(我使用 Express):
const socketBytes = new Map();
app.use((req, res, next) => {
req.socketProgress = getSocketProgress(req.socket);
next();
});
/**
* return kb read delta for given socket
*/
function getSocketProgress(socket) {
const currBytesRead = socket.bytesRead;
let prevBytesRead;
if (!socketBytes.has(socket)) {
prevBytesRead = 0;
} else {
prevBytesRead = socketBytes.get(socket).prevBytesRead;
}
socketBytes.set(socket, {prevBytesRead: currBytesRead})
return (currBytesRead-prevBytesRead)/1024;
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以req.socketProgress
在你的中间件中使用。
归档时间: |
|
查看次数: |
7874 次 |
最近记录: |