There are many libraries that you can use to make HTTP request in Node.js.
For this case we will create a simple HTTP request using axios.
Requirements:
Node.js project
Node package manager
Install axios using npm. Enter the following command in your terminal
npm install axios
Simple GET request
const axios = require('axios');
// Make a request to search a user with a given name
axios.get('/user?name=Mark')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
GET request without params manually keyed in the url
axios.get('/user', {
params: {
name: 'Mark'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
GET request using async and await
async function searchUser() {
try {
const response = await axios.get('/user?name=Mark');
console.log(response);
} catch (error) {
console.error(error);
}
}
Simple POST request
axios.post('/user', {
name: 'Mark'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});