use fetch in node js in javascript

In Node.js, you can use the node-fetch package to make HTTP requests using the fetch API.

Installation:

You can install the node-fetch package via npm. Run the following command in your terminal:

index.tsx
npm install node-fetch
23 chars
2 lines

Usage:

In your JavaScript file, require the module and make a fetch request to an API endpoint:

index.tsx
const fetch = require('node-fetch');

async function getData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  const data = await response.json();
  console.log(data);
}

getData();
216 chars
10 lines

In the example above, fetch method is used to reach out to https://jsonplaceholder.typicode.com/users. The response object will hold the returned data from the endpoint. To get the actual data, we take response object and call the json() method on it, which will parse the returned data.

Note that fetch method returns a promise, which is why the async/await syntax is used.

gistlibby LogSnag