Requests

Modern applications are heavily reliant on data retrieved from the Internet. Whether it's pulling user information from a database, getting the latest posts from an API, or sending form data to a server - at some point, you will need to start sending HTTP requests.

The fetch API provides a simple and Promise-based way to make HTTP requests. It works in virtually all modern browsers, and is natively supported by Node.js since version 18.

Loading TypeScript...

Links to child pages:

  • If you are using an older version of node, install node-fetch

The fetch response

Loading TypeScript...

Requesting text data

The simplest way to fetch data.

Loading TypeScript...

Fetching JSON data

The JSON Placeholder API provides a fast and reliable source for retrieving test data.

Loading TypeScript...

Posting data

Loading TypeScript...
Loading TypeScript...

Handling errors

The fetch API only rejects on network failures.

If the server responds with a 404 or 500 error, fetch still resolves the Promise and won't throw an error. To check if the request succeeded, check response.ok.

Loading TypeScript...

Sending headers

Setting headers

Loading TypeScript...

Handling large responses

Use the body as a stream instead of converting it all at once.

Loading TypeScript...

Uploading files

TODO: create this as a browser based example

Loading TypeScript...

Aborting a request

To cancel a request with an AbortController.

Loading TypeScript...

Parallel fetching with Promise.all

Manages multiple requests in parallel.

Loading TypeScript...

Fetch with retry

Loading TypeScript...

Writing JSON data to an API

Writes JSON data to an API.

Loading TypeScript...

Send a delete request

If an API endpoint supports DELETE requests, you can use fetch to execute a deletion request.

Loading TypeScript...

Was this page helpful?