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.ts23 chars2 lines
Then we can use the following code block to make a GET request to an API endpoint:
index.ts292 chars11 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.ts178 chars9 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