How to send get and post request in API using Node JS & using Postman

We can write get and post method in API using node js. We rae using Postman for testing here.

We can write API’s in node JS for send and recieving the requests.

const express = require('express');
const app = express();
const PORT = 5000;

// Parse JSON requests middleware should be registered before the routes that handle POST requests
app.use(express.json());
const friends = [
    { id: 0, name: 'tvdtdbwdubdwu21' },
    { id: 1, name: 'Testing2 mudndwmw' },
];

app.get('/friends', (req, res) => {
    res.json(friends);
});

app.get('/friends/:friendId', (req, res) => {
    const friendId = Number(req.params.friendId);
    const friend = friends[friendId];
    if (friend) {
        res.status(200).json(friend);
    } else {
        res.status(404).json({
            error: "File doesn't exist",
        });
    }
});

app.post('/friends', (req, res) => {
    if (!req.body.name) {
        res.status(400).json({
            error: 'Name doesnt exist',
        });
    } else {
        const newFriend = {
            name: req.body.name,
            id: friends.length,
        };
        friends.push(newFriend);
        res.json(newFriend);
    }
});

By using this code we can get the values in postman as well as in server.
First we need to install the Express and then define it above.
Now in postman , we just need to go on workspace section. There these methods are already their , we just need to select and GET/ POST and Click on send.
For eg: http://localhost:5000/friends
This will give the friends list , if we use the get method.

Leave a comment

Your email address will not be published. Required fields are marked *