

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- Sending Http Requests in ReactJS
- How to get HTTP Response Code using Selenium WebDriver?
- Checking HTTP Status Code in Selenium.
- Error Message: Unsupported xstream found: (“HTTP Code 200:OK”)” while consuming SAP Web Service
- Unreachable Code Error in Java
- Hamming code for single error correction, double error detection
- How to specify the HTTP method to use when sending form-data in HTML?
- How to send an error code using JSP to browser?
- Error Correcting Codes - Binary Convolutional Code
- Sending a Plain Message using Perl
- Sending an HTML Message using Perl
- Creating a QR Code of a link in React JS
- Using post request in middleware in express
- Sending an Attachment with email using Perl
- Sending an HTML e-mail using Python
Advertisements