Node.js http.ServerResponse.statusCode Property
Last Updated :
06 Apr, 2023
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
const http = require( 'http' );
const PORT = process.env.PORT || 3000;
const httpServer = http.createServer(
function (request, response) {
const value = response.statusCode;
response.end( "statusCode : " + value, 'utf8' , () => {
console.log( "displaying the result..." );
httpServer.close(() => {
console.log( "server is closed" )
})
});
});
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
const http = require( 'http' );
const httpHandlers = (request, response) => {
const value = response.statusCode;
response.end( "statusCode : " + value, 'utf8' , () => {
console.log( "displaying the result..." );
httpServer.close(() => {
console.log( "server is closed" )
})
});
};
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
Share your thoughts in the comments
Please Login to comment...