This article covers the topic of How to send get and post request in API using Node JS & using Postman
1. Install Axios:
First, we need to install the Axios library. we can do this by running the given command in our Node.js project directory:
npm install axios
2. Sending GET and POST Requests in Node.js:
Here’s how we can send GET and POST requests in Node.js using Axios:
// Import the Axios library
const axios = require('axios');
// Example GET request
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log('GET Request Response:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
// Example POST request
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => {
console.log('POST Request Response:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
This code sends a GET request to retrieve a post with ID 1 from JSONPlaceholder and a POST request to create a new post.
3. Testing with Postman:
To test these requests with Postman:
- Open Postman.
- Create a new request.
- Set the request type to GET or POST as needed.
- Enter the URL for the API endpoint you want to test.
- Click on “Send” to send the request.
- You should see the response in the Postman interface.
Thank you