Node.js has many packages to make HTTP request. There is one option is using node-fetch package. In this article we will see how to make HTTP request in Node.js using the node-fetch. It is same as window.fetch()
function.
node-fetch is a lightweight module that enables us to use the fetch() function in NodeJS.
Install node-fetch
Run the below command in Terminal to install node-fetch module in your project.
npm install node-fetch
Now you can create node-fetch instance:
const fetch = require('node-fetch');
GET request
Here we have make simple get request to fetch text from the laravelcode website.
const fetch = require('node-fetch');
const response = await fetch('https://laravelcode.com/');
const body = await response.text();
console.log(body);
POST request
You can make POST request with data like below:
const fetch = require('node-fetch');
const response = await fetch('https://api.laravelcode.com/users/create', {method: 'POST', body: 'name=usename&email=laravelcodeinfo@gmail.com'});
const data = await response.json();
console.log(data);
If you want to include Header, add Header array in second parameter.
const response = await fetch('https://api.laravelcode.com/users/create',{
method: 'POST',
body: 'name=usename&email=laravelcodeinfo@gmail.com',
headers: {'Content-Type': 'application/json'}
});
Conclusion
This way you can make HTTP requests in NodeJS using node-fetch module. I hope you liked this article.