Node.js response.writeHead() Method - GeeksforGeeks

23 Sep, 2020
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 modulevar http = require('http');  // Setting up PORTconst PORT = process.env.PORT || 3000;  // Creating http Servervar 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 ServerhttpServer.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 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']);  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 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...
[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
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 read and write Excel file in Node.js ?
How to use an ES6 import in Node.js?
Express.js res.render() Function
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript