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
var http = require( 'http' );
const PORT = process.env.PORT || 3000;
var httpServer = http.createServer(
function (request, response){
const body = 'hello world' ;
response.writeHead(200, {
'Content-Length' : Buffer.byteLength(body),
'Content-Type' : 'text/plain'
});
response.end(body);
});
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
var http = require( 'http' );
const PORT = process.env.PORT || 3000;
var httpServer = http.createServer(
function (request, response){
response.setHeader( 'Content-Type' , 'text/html' );
response.setHeader( 'Set-Cookie' , [ 'type=ninja' ,
'language=javascript' ]);
response.setHeader( 'X-Foo' , 'bar' );
response.writeHead(200,
{ 'Content-Type' : 'text/plain' });
const headers = response.getHeaders();
console.log(headers);
response.end( 'ok' );
});
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