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.ts150 chars5 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.ts215 chars9 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