- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Sending Http Requests in ReactJS
- Error Message: Unsupported xstream found: (“HTTP Code 200:OK”)” while consuming SAP Web Service
- How to get HTTP Response Code using Selenium WebDriver?
- Checking HTTP Status Code in Selenium.
- How to specify the HTTP method to use when sending form-data in HTML?
- How to send an error code using JSP to browser?
- Unreachable Code Error in Java
- Hamming code for single error correction, double error detection
- Error Correcting Codes - Binary Convolutional Code
- Getting error while running SAP oData service “HTTP Open failed: PLUGIN_NOT_ACTIVE”
- Sending a Plain Message using Perl
- Sending an HTML Message using Perl
- Can we get the HTTP Response Code in Selenium with Java?
- Sending an HTML e-mail using Python
- Sending an Attachment with email using Perl

Advertisements