Open In App
Related Articles

Node response.setHeader() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The `response.setHeader(name, value)` method, introduced in v0.4.0 of the ‘http‘ module, is used to set a single header value for implicit headers. If the header already exists in the headers to be sent, its value will be replaced. Multiple headers with the same name can be sent using an array of strings. Non-string values are stored as is, but when retrieved using `response.getHeader()`, they may appear as strings due to network transmission requirements. When headers are set with `response.setHeader()`, they are merged with any headers provided to `response.writeHead()`, with the latter taking precedence. Import the ‘http‘ module to use this functionality and obtain a proper response.

Syntax to Import:

const http = require('http');

Syntax:

response.setHeader(name, value)

Parameters: This property accepts a single parameter as mentioned above and described below:

  • name <String>: It accepts the name of the header and it is case-insensitive.
  • value <any>: It can accept any values like objects, string, integer, Array, etc. 

Return Value: It does not return any value, instead sets a header as described below.

Example 1: The below example illustrates the use of response.setHeader() property in Node.js.

javascript

// Node.js program to demonstrate the
// response.setHeaders() 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']);
 
  // Checking and  printing the headers
  console.log("When Header is set a string:",
  response.getHeader('Content-Type'));
  console.log("When Header is set an Array:",
  response.getHeader('Set-Cookie'));
   
  // Getting the set Headers
  const headers = response.getHeaders();
   
  // Printing those headers
  console.log(headers);
 
  // Prints Output on the browser in response
  response.writeHead(200,
    { 'Content-Type': 'text/plain' });
  response.end('ok');
});
 
// Listening to http Server
httpServer.listen(PORT, () => {
    console.log("Server is running at port 3000...");
});

                    

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

In Console
>> Server is running at port 3000...
>> When Header is set a string: text/html
>> When Header is set an Array: ['type=ninja', 'language=javascript']
>> [Object: null prototype]
{ 'content-type' : 'text/html', 'set-cookie' : ['type=ninja', 'language=javascript']}

Example 2: The below example illustrates the use of response.setHeader() property in Node.js.

Javascript

// Node.js program to demonstrate the
// response.setHeaders() 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 (req, response) {
 
        // Setting up Headers
        response.setHeader('Alfa', 'Beta');
        response.setHeader('Alfa1', '');
        response.setHeader('Alfa2', 5);
        response.setHeader('Cookie-Setup',
            ['Alfa=Beta', 'Beta=Romeo']);
        // response.setHeader('', 'Beta'); // Throws Error
        // response.setHeader(); // Throws Error
 
        // Checking and printing the headers
        console.log("When Header is set an Array:",
            response.getHeader('Cookie-Setup'));
        console.log("When Header is set an 'Beta':",
            response.getHeader('Alfa'));
        console.log("When Header is set '':",
            response.getHeader('Alfa1'));
        console.log("When Header is set number 5:",
            response.getHeader('alfa2'));
        console.log("When Header is not set:",
            response.getHeader('Content-Type'));
 
        // Getting the set Headers
        const headers = response.getHeaders();
 
        // Printing those headers
        console.log(headers);
 
        var Output = "Hello Geeksforgeeks..., "
            + "Available headers are:"
            + JSON.stringify(headers);
 
        // Prints Output on the browser in response
        response.write(Output);
        response.end('ok');
    });
 
// Listening to http Server
httpServer.listen(PORT, () => {
    console.log("Server is running at port 3000...");
});

                    

Steps to run the node server:

node index.js

Output:

Server is running at port 3000...
When Header is set an Array: [ 'Alfa=Beta', 'Beta=Romeo' ]
When Header is set an 'Beta': Beta
When Header is set '':
When Header is set number 5: 5
When Header is not set: undefined
[Object: null prototype] {
alfa: 'Beta',
  alfa1: '',
  alfa2: 5,
  'cookie-setup': [ 'Alfa=Beta', 'Beta=Romeo'
]}

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

Hello Geeksforgeeks..., Available headers are:
{"alfa":"Beta", "alfa1":"", "alfa2":5, "cookie-setup":["Alfa=Beta", "Beta=Romeo"]}ok

Avoid using `response.writeHead()` without prior usage to prevent immediate writing of header values to the network channel. For progressive header population with future retrieval and modification, favor `response.setHeader()` over `response.writeHead()`.



Last Updated : 15 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads