How to Use Handle Get Request in Express.js ?
Last Updated :
29 Jul, 2024
Express.js is a popular web application framework for Node.js, known for its simplicity and flexibility. One of the fundamental tasks in web development is handling HTTP requests, and GET requests are among the most common. This article will guide you through the process of handling GET requests in Express.js, covering the basics, practical examples, and best practices.
Introduction to GET Requests
A GET request is used to retrieve data from a server. When a client sends a GET request, it is asking the server to fetch a resource without causing any side effects. GET requests are typically used for:
- Fetching web pages
- Retrieving data from APIs
- Downloading files
Syntax:
app.get( path, callback )
Parameters: Â
- path: It is the path for which the middleware function is being called.
- callback: They can be a middleware function or a series/array of middleware functions.
Note: One of the advantages of using the express.js middleware we can forward the incoming request using next() function present in the every request handling functions of the express.js. Refer this article.
Approach
To handle GET requests in Express.js, create an Express app, define a route using app.get('/path', callback)
, and use the callback to process the request and send a response.
Steps to to Handle GET Request
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2:Â Navigate to the project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Step 3:Â Install the necessary packages/libraries in your project using the following commands.
npm install express
Project Structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.19.2",
}
Example: Implementation to show the use handle get request in Express.js.
Node
// app.js
// Importing expresss
const express=require("express")
const app=express();
// Handling get request
app.get("/get",(req,res,next)=>{
res.send("This is the get request");
})
app.get("/get/users",(req,res,next)=>{
res.send("This is the get/users request")
})
app.listen(3000,()=>{
console.log("Server is Running");
})
Step to Run Application:Â Run the application using the following command from the root directory of the project
node app.js
Output: In your browser type localhost:8000/get you will set below response
Example 2: In this example, we will see how to send the HTML response in the get request.Â
Node
// app.js
//Importing expresss
const express=require("express")
const app=express();
// Handling get request
app.get("/get",(req,res,next)=>{
// Sending inline html response
res.send("<h1>Get Response</h1>")
})
app.listen(3000,()=>{
console.log("Server is Running");
})
Step to Run Application:Â Run the application using the following command from the root directory of the project
node app.js
Output: In your browser type localhost:8000/get you will set below response