Async

JS Fetch API

Using the Fetch API

JavaScript Fetch API retrieves data, with headers and CORS handling.

Introduction to Fetch API

The Fetch API provides a modern, promise-based mechanism to make network requests in JavaScript. It is an improvement over XMLHttpRequest, offering a more powerful and flexible feature set to handle HTTP requests and responses.

Basic Fetch Request

A basic Fetch request can be made using the fetch() method, which returns a promise that resolves to the response of the request. This response can then be converted into various formats such as JSON.

Handling Headers

You can add custom headers to your Fetch request using the Headers interface. This is useful for setting content types, authentication tokens, and more.

Handling CORS

Cross-Origin Resource Sharing (CORS) is a security feature that allows or restricts requested resources on a web server depending on where the HTTP request was initiated. The Fetch API respects CORS policies, and you'll need to configure the server to accept requests from your origin.
By default, Fetch requests make "simple requests" which are safe and not preflighted. However, for "non-simple requests", the server must respond with appropriate headers.

Error Handling with Fetch

Unlike XMLHttpRequest, the Fetch API does not reject promises upon HTTP error statuses (such as 404 or 500). Instead, you need to check the response.ok property to determine if the request was successful.

Using Fetch with Async/Await

You can use async/await with Fetch to write cleaner asynchronous code. This allows you to write code that looks synchronous, making it easier to read and maintain.

Previous
Async/Await
Next
AJAX