Open In App

Node.js http.ServerResponse.statusCode Property

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The httpServerResponse.statusCode is an inbuilt application programming interface of class ServerResponse within the HTTP module which is used to this property controls the status code that will be sent to the client when the headers get flushed.

Syntax:

const response.statusCode

Parameters: This property does not accept any arguments as a parameter.

Return Value: This property returns the status code that will be sent to the client.

Example 1: Filename-index.js

Javascript




// Node.js program to demonstrate the
// response.statusCode method
 
// Importing http module
const http = require('http');
 
// Setting up PORT
const PORT = process.env.PORT || 3000;
 
// Creating http Server
const httpServer = http.createServer(
    function (request, response) {
 
        // Getting the statusCode
        // by using statusCode method
        const value = response.statusCode;
 
        // Display result by using end() method
        response.end("statusCode : " + value, 'utf8', () => {
            console.log("displaying the result...");
 
            httpServer.close(() => {
                console.log("server is closed")
            })
        });
    });
 
// Listening to http Server
httpServer.listen(PORT, () => {
    console.log("Server is running at port 3000...");
});


Run the index.js file using the following command:

node index.js

Output:

Server is running at port 3000...
displaying the result...
server is closed

Now open your browser and go to http://localhost:3000/, you will see the following output:

statusCode : 200

Example 2: Filename-index.js

Javascript




// Node.js program to demonstrate the
// response.statusCode method
 
// Importing http module
const http = require('http');
 
// Request and response handler
const httpHandlers = (request, response) => {
 
    // Getting the statusCode
    // by using statusCode method
    const value = response.statusCode;
 
    // Display result by using end() method
    response.end("statusCode : " + value, 'utf8', () => {
        console.log("displaying the result...");
 
        httpServer.close(() => {
            console.log("server is closed")
        })
    });
};
 
// Creating http Server
const httpServer = http.createServer(
    httpHandlers).listen(3000, () => {
        console.log("Server is running at port 3000...");
    });


Run the index.js file using the following command:

node index.js

Output:

Server is running at port 3000...
displaying the result...
server is closed

Now open your browser and go to http://localhost:3000/, you will see the following output:

statusCode : 200

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_statuscode



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads