Sending HTTP error code using Express.js



We can send different HTTP status and responses over the Express.js app endpoint as per the user's requirement. Also we can send a message in case of an error or when the requests are forbidden. The status code 200 is sent by default with the response returned.

Syntax

res.status( statusCode )

Example 1

Create a file with the name "status.js" and copy the following code snippet. After creating the file, use the command "node status.js" to run this code as shown in the example below −

// Specifying status code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating an endpoint
app.get("/api", (req, res) => {
   res.status(400);
   res.send("Bad Request Received")
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following URL endpoint with a GET request – localhost:3000/

Output

Bad Request Received

Example 2

Let's take a look at one more example.

// Specifying status code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Creating an endpoint
app.get("/api", (req, res) => {
   res.status(403);
   res.send("This API Endpoint is forbidden")
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following URL endpoint with a GET request – localhost:3000/

Output

This API Endpoint is forbidden

Advertisements