Express: Specify HTTP status code when throwing error in service
Last Updated :
02 Aug, 2024
In express, we can use res.status(--statusCode--) to set the status code. Let's create a simple web application using express and create a blog route, and when the user tries to access that route it will send the status code.
Syntax:
res.status(--statusCode--);
where you have to change the --statusCode-- to the code you want to set.
Creating Application:
Step 1: Initializes NPM: Create and Locate your project folder in the terminal & type the command
npm init -y
It initializes our node application & makes a package.json file.
Step 2: Install Dependencies: Locate your root project directory into the terminal and type the command
npm install express
To install Express as dependencies inside your project
Step 3: Creating Routes for the home page and the blog page: Let's create two routes so that users can access the home page and the blog page.
app.get('/', (req, res) => {
res.send('Hello Geeks!');
});
app.get('/blog', (req, res) => {
res.status(400);
res.send('Error');
});
Inside blog routes we use res.status function to set the status code to 400 which throws when the user requests for the blog page.
Example 1:
JavaScript
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello Geeks!');
});
app.get('/blog', (req, res) => {
res.status(400);
res.send('Error');
});
app.listen(3000);
Steps to run the application: Inside the terminal type the command to run your script.
node app.js
Output:
Creating Application:
Step 1: Initializes NPM: Create and Locate your project folder in the terminal & type the command
npm init -y
It initializes our node application & makes a package.json file.
Step 2: Install Dependencies: Locate your root project directory into the terminal and type the command
npm install express
To install Express as dependencies inside your project
Step 3: Creating list of products: Let's create an array of products and set it to a constant products.
const products = ["Milk", "Sugar"];
Step 4: Creating Routes for the home page and the products page: Let's create two routes so that users can access the home page and the products page.
app.get('/', (req, res) => {
res.send('Hello Geeks!');
});
app.get('/products', (req, res) => {
if (products.length === 0) {
res.status(400);
res.send('No products found!');
} else {
res.json(products);
}
});
Inside the product route, we use res.status function to set the status code to 400 which throws when there is no product. If there are products it will send the list as JSON.
Example 2:
JavaScript
const express = require('express');
const app = express();
const products = ["Milk", "Sugar"];
app.get('/', (req, res) => {
res.send('Hello Geeks!');
});
app.get('/products', (req, res) => {
if (products.length === 0) {
res.status(400);
res.send('No products found!');
} else {
res.json(products);
}
});
app.listen(3000);
Steps to run the application: Inside the terminal type the command to run your script.
node app.js
Output:
Similar Reads
How to get Response Status Code with Selenium WebDriver?
In web automation and testing, obtaining the HTTP response status code is crucial for validating the accessibility and health of web pages. While Selenium WebDriver is widely recognized for its powerful capabilities in automating browser interactions, it does not directly provide methods for fetchin
4 min read
How to resolve req.body is empty in posts error in Express?
In Express the req.body is empty error poses a critical challenge in web development, particularly in the context of processing POST requests on the server side. This issue arises when the server encounters difficulties parsing the request body, resulting in an empty or undefined req.body object. De
4 min read
How to Use Spring @ResponseStatus to Set HTTP Status Code?
In a Spring Boot application, handling HTTP responses with the appropriate status code is crucial for communicating the outcome of a request to the client. The @ResponseStatus annotation in Spring allows developers to set the HTTP status code directly from a controller or exception handler. This app
4 min read
How to Redirect 404 errors to a page in Express.js ?
Express Js is a web application framework based on Node.js web server functionality that helps us to create web servers with lesser complexity and in a well-organized manner. Express provides routing services that help us in creating application endpoints that respond based on the HTTP request metho
3 min read
HTTP status codes | Client Error Responses
The browser and the site server have a conversation in the form of HTTP status codes. The server gives responses to the browserâs request in the form of a three-digit code known as HTTP status codes. The categorization of HTTP status codes is done in five sections which are listed below. Information
4 min read
Which HTTP response status codes result in then() and which in catch() ?
Axios is a popular JavaScript library for making HTTP requests. It uses promises to handle the response from the server, and provides a convenient then() and catch() syntax for working with the data or handling errors. Have you ever wondered which HTTP response status codes will cause axios to call
4 min read
How to add a 404 Error Page in the Express ?
Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will discuss how to add a 404 error page i.e not found using the express server. 404 is the
1 min read
Express Returns Servers HTML Error Page Instead of res.json Error Message
When building APIs with Express.js, you might encounter a situation where instead of returning a JSON error message, your server returns an HTML error page. This can be frustrating, especially when your application relies on consistent JSON responses. In this article, we'll explore why this happens
4 min read
How to set Error.code property in Node.js v12.x ?
Setting setError.code property in Node.js v12.x or above is a bit complex process, but In this article, you will learn to do this in a very easy way.Problem Statement: Sometimes we want to set the error code manually, we want to show our own error code instead of a pre-built error code when throwing
2 min read
Requesting in http vs Requesting in Express.js
Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that Node.js is not a framework and itâs not a programming language. Most people are confused and understand itâs a framework or a programming language. We
3 min read