在发送响应之前,我的node.js Koa服务器如何检测和记录客户端断开连接。
通常顺序是:
request
如果客户端在2完成后断开连接,但在4完成之前,node.js Koa能检测并记录这一点吗?
我使用这个简单的脚本进行了测试,并从另一个终端运行curl,然后在node.js睡眠的10秒延迟期间,终止ctrl命令。
const Koa = require('koa');
const app = new Koa();
/**
* synchronously delay/sleep/block for time ms
*/
const delay = time => new Promise(res=> {
console.log(`About to sleep for ${time} ms`)
setTimeout(res,time)
});
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
app.use(async ctx => {
ctx.req.on('close', () => {
console.log('Request closed');
});
console.log('Hello World Started')
await delay(10000)
console.log('Hello World Ended');
ctx.body = 'Hello World !!!';
});
app.listen(3000, () => console.log('running on port 3000'));在这两种情况下,只发出一次ctx.req.on('close'事件:
我正在使用:
node --version
v13.8.0讨论不同版本的节点何时发出req.on(“关闭”)事件,此处为:https://github.com/nodejs/node/issues/31394。
假设没有特定的“客户端在您发送响应之前断开连接”事件,那么什么是最好的模式来检测一般情况,这样我就可以记录它。
发布于 2020-05-14 01:47:50
我们可以用一个变量来评估这个问题。当客户端在请求处理完成之前关闭时,下面提到的代码将记录错误消息。这是一种肮脏的修复,但有效。
const Koa = require('koa');
const app = new Koa();
/**
* synchronously delay/sleep/block for time ms
*/
const delay = time => new Promise(res=> {
console.log(`About to sleep for ${time} ms`)
setTimeout(res,time)
});
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
app.use(async ctx => {
let requestProcessingCompleted = false
ctx.req.on('close', () => {
console.log('Request closed');
if(!requestProcessingCompleted){
console.log("Client connection closed before request processing completed")
}
});
console.log('Hello World Started')
await delay(10000)
console.log('Hello World Ended');
ctx.body = 'Hello World !!!';
requestProcessingCompleted = true
});
app.listen(3000, () => console.log('running on port 3000'));https://stackoverflow.com/questions/61745372
复制相似问题