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.
Links to child pages:
- If you are using an older version of node, install
node-fetch
The fetch response
Requesting text data
The simplest way to fetch data.
Fetching JSON data
The JSON Placeholder API provides a fast and reliable source for retrieving test data.
Posting data
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.
Sending headers
Setting headers
Handling large responses
Use the body as a stream instead of converting it all at once.
Uploading files
TODO: create this as a browser based example
Aborting a request
To cancel a request with an AbortController.
Parallel fetching with Promise.all
Manages multiple requests in parallel.
Fetch with retry
Writing JSON data to an API
Writes JSON data to an API.
Send a delete request
If an API endpoint supports DELETE requests, you can use fetch to execute a deletion request.