Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
Is 'res.writeHead' necessary? Does it have a purpose?

I am writing a bare minimal node.js server to understand how it works. From what I can tell this line:

res.writeHead(200);

does nothing. If I remove it I get the exact same behavior from the browser. Does it have any purpose? Is it OK to remove it?

// https://nodejs.dev/learn/the-nodejs-http-module

const http = require('http');
const server = http.createServer(handler);

server.listen(3000, () => {
  console.log('node: http server: listening on port: ' + 3000);
});

function handler(request, response) {
  res.writeHead(200);
  res.end('hello world\n');
}

Is it some how related to http headers?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The default http status is 200, so you do not have to tell the response object that the status is 200. If you don't set it, the response will automatically be 200. You can remove res.writeHead(200); and similarly, you don't need the express version of that which would be res.status(200).

The other thing that res.writeHeader(200) does is cause the headers to be written out in the response stream at that point. You also don't need to call that yourself because when you do res.send(...), the headers will automatically be sent first (if they haven't already been sent). In fact, the res.headersSent property keeps track of whether the headers have been sent yet. If not, they are sent as soon as you call any method that starts sending the body (like res.send() or res.write(), etc...).

Is it OK to remove it?

Yes, in this context it is OK to remove it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda