Skip to content
Related Articles

Related Articles

Improve Article

How to use handle get request in Express.js ?

  • Last Updated : 15 Sep, 2021
Geek Week

Introduction: Express.js is the most powerful framework of node.js. It is a routing and Middleware framework for handling the different routing of the webpage, and it works between the request and response cycle. It uses different kinds of middleware functions in order to complete the different requests made by the client for Eg. clients can make get, put, post, and delete requests these requests can easily handle by these middleware functions. 

In this article, we will discuss how to handle get requests in the express.js, app.get() method of the express.js is used to handle the incoming get request from the client-side Basically is it intended for binding the middleware to your application.

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 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.



Let’s see step-by-step implementation.

Step 1: Create npm project and empty package.json file.

npm init

Step 2: Install the express module using the following command.

npm install express

Project structure: Our project structure will look like the following.

Example 1: In this example, we will create a route with get request and without get request forwarding.

Filename: index.js

Javascript






// 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(8000,()=>{
    console.log("Sever is Running");
})

 
Step to run the application: Open the terminal and run index.js file using below command:

node index.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. 

Filename: index.js

Javascript




//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(8000,()=>{
    console.log("Sever is Running");
})

Step to run the application: Open the terminal and run index.js file using below command:

node index.js

Output: In your browser type localhost:8000/get you will set below response

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :