【问题标题】:How to write HTTP 500 error header after the fact事后如何编写 HTTP 500 错误标头
【发布时间】:2018-10-22 04:47:27
【问题描述】:

说我有这个:

const writeResponse = function(file: string, s: Socket){

   s.write([
    'HTTP/1.1 200 OK',
    'Content-Type: text/javascript; charset=UTF-8',
    'Content-Encoding: UTF-8',
    'Accept-Ranges: bytes',
    'Connection: keep-alive',
   ].join('\n') + '\n\n');

  getStream(file)
    .once('error', function (e: any) {
      s.end('error: ' + e && e.stack || e.message || util.inspect(e));
    })
    .pipe(s)
    .once('error', function (e: any) {
      s.end('error: ' + e && e.stack || e.message || util.inspect(e));
    });

}

我无法弄清楚如何解决的问题 - 如果读取文件时出错,我如何发送此标头而不是成功标头:

HTTP/1.1 500 Cannot read file

问题是,据我所知,将文件写入响应必须在写入标头之后进行,但是如果读取文件时出错怎么办?

【问题讨论】:

标签: node.js http express fs http-status-code-500


【解决方案1】:

有两种可能:

  • 应用程序会保留标题,直到不会发生错误(例如,整个文件已被缓冲)。在这种情况下,应用将能够发送 5xx 错误。
  • 如果应用程序发送 200 标头,向另一端发出错误信号的唯一可能方法是发送截断响应。这只能通过chunked transfer-encoding:content-length: 实现。使用 connection:close 无法判断 HTTP 级别是否存在错误。

【讨论】:

    猜你喜欢
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2018-10-22
    • 2019-03-24
    • 2018-02-28
    相关资源
    最近更新 更多