我有一个expressjs服务器,它使用sendFile函数将文件发送到客户端。我使用函数的回调来了解何时发生错误。现在看来,每当 sendFile 决定响应 304(在我的情况下这是所需的行为)时,它的回调就会被调用,并出现以下错误:
Error: Request aborted: sendFile error
at Object._onImmediate (.../node_modules/express/lib/response.js:941:17)
at processImmediate [as _immediateCallback] (timers.js:336:15)
{ [Error: Request aborted: sendFile error] code: 'ECONNABORT' }
但是,我找不到任何有关此错误的文档,我想知道如何确定何时忽略此错误以及何时对其使用react,因为似乎可能存在其他情况,此类错误是问题的症状,不仅仅是期望行为的副作用。
这确实是 sendFile 应该做的事情吗?有这方面的文档吗?如何区分此错误和其他 ECONNABORT 错误?
最佳答案
response.statusCode 可以帮助检测这种情况,但我不知道这是否也会捕获其他错误。这是我修改后的代码,改编自 the docs
res.sendFile(filename, options, function (err) {
if (err) {
if (err.code === "ECONNABORT" && res.statusCode == 304) {
// No problem, 304 means client cache hit, so no data sent.
console.log('304 cache hit for ' + filename);
return;
}
console.error("SendFile error:", err, " (status: " + err.status + ")");
if (err.status) {
res.status(err.status).end();
}
}
else {
console.log('Sent:', filename);
}
关于node.js - 为什么express的sendFile函数将304视为错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26049466/