Open In App

How to test GET Method of express with Postman ?

Last Updated : 01 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The GET method is mainly used on the client side to send a request to a specified server to get certain data or resources. By using this GET method we can only access data but can’t change it, we are not allowed to edit or completely change the data. It is widely one of the most used methods. In this article, you are going to learn how to use the GET Method in Express. This article will cover syntax and examples to help you use this method.

Prerequisites:

The following approaches will be discussed to test the GET method:

1. Testing Basic GET request:

It is used to Handle a basic GET request in Express. One of the main reasons for its wide use is because of its simple and straightforward behaviour.

Syntax:

app.get('/', (req, res) => {
res.send('Hello, this is a basic GET request!');
});

Example: In this example we will see the Basic GET request

Javascript




const express = require("express");
const app = express();
let port = 8080;
 
app.listen(port, () => {
    console.log(`server is running on port ${port}`);
});
 
app.get("/", (req, res) => {
    res.send("your request is successful");
});


Output:

postNode1GIF

Output

2. Testing GET Request with Route Parameters:

We can say it is an advanced version of Basic GET request as we define a route with a parameter placeholder (e.g: id) in the URL

To access the parameter defined in URL we use ‘req.params’ in the route handler function.

Syntax:

app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`Fetching user with ID: ${userId}`);
});

Example: Utilize the captured parameter to customize the response based on the value.

Javascript




const express = require("express");
const app = express();
let port = 8080;
 
app.listen(port, () => {
    console.log(`server is running on port ${port}`);
});
 
app.get("/user/:id", (req, res) => {
    const userId = req.params.id;
    res.send(`Fetching user with ID: ${userId}`);
});


Output:

postNodeGIF

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads