我的node.js Koa服务器如何在发送响应之前检测并记录客户端已断开连接。
通常顺序是:
如果客户端在2完成之后但在4完成之前断开连接,node.js Koa可以检测并记录吗?
我已经使用这个简单的脚本并从另一个终端运行curl进行了测试,然后在node.js进入睡眠状态的10秒钟延迟期间,我终止(ctrl-c)curl命令。
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('close')事件:https://github.com/nodejs/node/issues/31394。
假设没有特定的“客户端在发送响应之前已断开连接”事件,那么通常检测这种情况的最佳模式是什么,因此我可以对其进行记录。
答案 0 :(得分:1)
我们可以使用变量进行评估。当客户端在请求处理完成之前关闭时,下面提到的代码记录错误消息。这是一个肮脏的修复程序,但它可以工作
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'));