createServer:发送到客户端后无法设置 headers

createServer: Cannot set headers after they are sent to the client

我试图在我的 http 服务器上配置 MIME 类型并将 Content-Type 设置为 text/html,但我收到此错误:

(node:87702) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我的代码是这样的:

const handler = require('serve-handler');
const http = require('http');

const server = http.createServer((request, response) => {
  response.statusCode = 200;
  response.setHeader('Content-Type', 'text/html');
  response.end();

  handler(request, response);
})

server.listen(3000, () => {
  console.log('Running at http://localhost:3000');
});

我几乎复制了 library's (serve) README 中的示例。

我没有太多这方面的经验来理解我做错了什么,任何帮助将不胜感激。

您将以 response.end() 结束回复。这意味着 head 和 body 已经发送给客户端。因此,handler,当它运行时,当它尝试设置响应属性时,它将无法设置,因为响应已经发送。

我猜你不需要 response.end()。不清楚它有什么用。

(node:87702) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

尝试将这条线 handler(request, response) 向上移动,如下所示:

const server = http.createServer((request, response) => {
  handler(request, response); //move here

  response.statusCode = 200;
  response.setHeader('Content-Type', 'text/html');
  response.end();
})

因为 response.end() 语句:

This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete.

因此,当handler(request, response) 中间件试图将headers 设置为响应时,就会发生错误。