![]() |
VOOZH | about |
The response.setHeader() method in Node.js is used to set HTTP headers for a response. It allows you to define one or more headers for the HTTP response sent by the server. If a header with the same name already exists, its value will be replaced. Additionally, headers can be set as an array of values, especially useful for headers like Set-Cookie, which may require multiple values.
response.setHeader(name, value)Parameters: This property accepts a single parameter as mentioned above and described below:
Return Value: This method does not return any value. It simply sets the header as described.
Example 1: In this example, we set a few headers and retrieve them using response.getHeader().
Output: Now run http://localhost:3000/ in the browser.
Server is running at port 3000...
When Header is set as a string: text/html
When Header is set as an Array: ['type=ninja', 'language=javascript']
[Object: null prototype]
{ 'content-type': 'text/html', 'set-cookie': ['type=ninja', 'language=javascript']}
Example 2: In this example, various types of headers (string, empty string, number, and array) are set and retrieved.
Output:
Server is running at port 3000...
When Header is set as an Array: [ 'Alfa=Beta', 'Beta=Romeo' ]
When Header is set as 'Beta': Beta
When Header is set as '':
When Header is set as 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
The response.setHeader() method in Node.js is a useful way to set HTTP headers for a response. It allows you to add or modify headers before sending the response. For most use cases, it's better to use setHeader() for progressively adding headers, rather than using writeHead() immediately, as it gives you more flexibility and control over the headers.