Open In App
Related Articles

Node.js response.writeHead() Method

Improve Article
Improve
Save Article
Save
Like Article
Like

The response.writeHead() (Added in v1..0) property is an inbuilt property of the ‘http’ module which sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.

When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence. If this method is called and response.setHeader() has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If the progressive population of headers is desired with potential future retrieval and modification, use response.setHeader() instead.

In order to get a response and a proper result, we need to import ‘http’ module.

Import:

const http = require('http');

Syntax:

response.writeHead(statusCode[, statusMessage][, headers]);

Parameters: It accepts three parameters as mentioned above and described below:

  • statusCode <number>: It accepts the status codes that are of number type.
  • statusMessage <string>: It accepts any string that shows the status message.
  • headers <Object>: It accepts any function, array, or string.

Return Value <http.ServerResponse>: It returns a reference to the ServerResponse, so that calls can be chained.

The below example illustrates the use of response.writeHead() property in Node.js.

Example 1: Filename: index.js




// Node.js program to demonstrate the 
// response.writeHead() Method
  
// Importing http module
var http = require('http');
  
// Setting up PORT
const PORT = process.env.PORT || 3000;
  
// Creating http Server
var httpServer = http.createServer(
        function(request, response){
  
  const body = 'hello world';
    
  // Calling response.writeHead method
  response.writeHead(200, {
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'text/plain'
  });
    
  response.end(body);
});
  
// Listening to http Server
httpServer.listen(PORT, () => {
   console.log("Server is running at port 3000...");
});


Output:

Output: In-Console

Server is running at port 3000…

Now run http://localhost:3000/ in the browser.

Output: In-Browser

hello world

Example 2: Filename: index.js




// Node.js program to demonstrate the 
// response.writeHead() Method
  
// Importing http module
var http = require('http');
  
// Setting up PORT
const PORT = process.env.PORT || 3000;
  
// Creating http Server
var httpServer = http.createServer(
        function(request, response){
  
  // Setting up Headers  
  response.setHeader('Content-Type', 'text/html');
  response.setHeader('Set-Cookie', ['type=ninja'
  'language=javascript']);
  response.setHeader('X-Foo', 'bar');
  
  // Calling response.writeHead method
  response.writeHead(200, 
     { 'Content-Type': 'text/plain' });
  
  // Getting the set Headers
  const headers = response.getHeaders();
    
  // Printing those headers
  console.log(headers);
  
  // Prints Output on the 
  // browser in response
  response.end('ok');
});
  
// Listening to http Server
httpServer.listen(PORT, () => {
   console.log(
"Server is running at port 3000...");
});


Run index.js file using the following command:

node index.js

Output:

Output: In-Console

Server is running at port 3000…

[Object: null prototype] {

 ‘content-type’: ‘text/plain’,

 ‘set-cookie’: [ ‘type=ninja’, ‘language=javascript’ ],

 ‘x-foo’: ‘bar’}

Now run http://localhost:3000/ in the browser.

Output: In-Browser

ok

Content-Length is given in bytes, not characters. Use Buffer.byteLength() to determine the length of the body in bytes. Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not. Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.

Reference: https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 23 Sep, 2020
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials