create a get request using node fetch in typescript

To create a GET request using node-fetch package in TypeScript, we first need to install the package by running the following command in our project directory:

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

Then we can use the following code block to make a GET request to an API endpoint:

index.ts
import fetch from 'node-fetch';

async function getRequest(url: string): Promise<any> {
  const response = await fetch(url, { method: 'GET' });
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const result = await response.json();
  return result;
}
292 chars
11 lines

In this code block, we first import the node-fetch module which provides a global fetch function that we can use to make requests. Then we define an async function called getRequest that takes a url parameter and returns a Promise that resolves to the JSON data returned by the API.

Inside the function, we use fetch to make a GET request to the specified url. If the response is not OK (i.e. the status code is not in the 200-299 range), we throw an error. Otherwise, we parse the JSON data from the response and return it.

Example Usage:

index.ts
const apiUrl = 'https://jsonplaceholder.typicode.com/posts';
getRequest(apiUrl)
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });
178 chars
9 lines

This code block makes a GET request to https://jsonplaceholder.typicode.com/posts and logs the response data to the console. If there's any error while making the request, it logs the error to the console.

gistlibby LogSnag