create a get request in typescript

To create a GET request in TypeScript, you can use the built-in fetch API. Here's an example of how to make a GET request to an API endpoint and parse the JSON response:

index.ts
fetch('https://example.com/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
150 chars
5 lines

In this code block, we're using the fetch method to make a GET request to 'https://example.com/api/data'. After we receive the response, we call the json method to parse the response as JSON data. Finally, we log the parsed data to the console. If there is an error, we log the error to the console as well using the catch method.

You can also provide additional options to the fetch method, such as setting headers, providing authentication, or using a different HTTP method. Here's an example of adding a header to our GET request:

index.ts
fetch('https://example.com/api/data', {
  headers: {
    Authorization: 'Bearer <access_token>'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
215 chars
9 lines

In this code block, we're setting the Authorization header to include an access token using the Bearer scheme. You can modify the headers object to suit your needs.

gistlibby LogSnag