Node.js response.setHeader() Method - GeeksforGeeks

15 Sep, 2020
The response.setHeader(name, value) (Added in v0.4.0) method is an inbuilt application programming interface of the ‘http‘ module which sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here to send multiple headers with the same name. Non-string values will be stored without modification. Therefore, response.getHeader() may return non-string values. However, the non-string values will be converted to strings for network transmission.
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.
In order to get a response and a proper result, we need to import ‘http’ module.
Syntax:
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.
The below example illustrates the use of response.setHeader() property in Node.js.
Example 1: Filename: index.js
// Node.js program to demonstrate the // response.setHeaders() Method  // Importing http modulevar http = require('http');// Setting up PORTconst PORT = process.env.PORT || 3000;  // Creating http Servervar 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 ServerhttpServer.listen(PORT, () => {    console.log("Server is running at port 3000...");});
Now run http://localhost:3000/ in the browser.
Output:
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: Filename: index.js
// Node.js program to demonstrate the // response.setHeaders() Method  // Importing http modulevar http = require('http');  // Setting up PORTconst PORT = process.env.PORT || 3000;  // Creating http Servervar 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 ServerhttpServer.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...
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’ ]}
Now run http://localhost:3000/ in the browser.
Output: In Browser
Hello Geeksforgeeks..., Available headers are:{“alfa”:”Beta”, “alfa1′′:””, “alfa2”:5, “cookie-setup”:[“Alfa=Beta”, “Beta=Romeo”]}ok
If response.writeHead() method is called and this method 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 progressive population of headers is desired with potential future retrieval and modification, use response.setHeader() instead of response.writeHead().
Reference: https://nodejs.org/api/http.html#http_response_setheader_name_value
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.render() Function
Mongoose | findByIdAndUpdate() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript