node.js - 为什么express的sendFile函数将304视为错误?

标签 node.js express http-status-code-304

我有一个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/

相关文章:

mysql - Sequelize 运行脚本文件

javascript - 使用nodejs管道流下载大文件会导致大量内存使用和OOM错误

http - 304 未修改为 200(来自缓存)

jquery - 为什么在获取 304 状态码时,jquery ajax 不调用从缓存中填充数据变量?

node.js - 如何为服务器定位 ES6 并为客户端定位 ES5

node.js - promise 似乎没有按正确的顺序调用?

javascript - Nodejs - Express res.download 发送异常后无法设置 header

http - 为什么我在使用 HttpWebRequest 时在某些链接上收到 "(304) Not Modified"错误?

node.js - 任何使用 mongo db 完成用户集成的 node.js 示例?

javascript - 在中间件中获取响应状态码