How to Create HTTP request in Node.js using node-fetch module

  1000 views   4 months ago NodeJS

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 protected]'});

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 protected]',
    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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]