Search code examples
httphttpserver

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


I'm trying to configure the MIME type on my http server and set the Content-Type to text/html, but I'm receiving this error:

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

This is what my code looks like:

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');
});

I've pretty much copied the example from the library's (serve) README.

I don't have much experience with this to understand what I'm doing wrong, any help would be appreciated.


Solution

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

    Try to move this line handler(request, response) upward, like so:

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

    Because of response.end() statement:

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

    Therefore, when the handler(request, response) middleware trying to set headers to the response, the error occurs.