JavaScript Course
JavaScript
/
Intermediate

Fetch API

Definition

The Fetch API provides an interface for fetching resources (including across the network). It is a more powerful and flexible replacement for XMLHttpRequest (XHR) and heavily relies on Promises.

Explain Like I'm New

Fetch is JavaScript's built-in delivery service. You give it a web address (URL), and it goes out to the internet, gets the data (like a JSON file or an image), and brings it back to your code.

Real World Example

When you log into a website, the browser uses Fetch to send your username and password to the server, and the server uses the response to tell the browser whether the login was successful.

Common Use Cases

  • •Requesting data from REST APIs
  • •Submitting form data without refreshing the page
  • •Downloading files or images dynamically

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What does the fetch() function return?
  • How do you parse a JSON response using fetch?

intermediate

  • How do you send a POST request with fetch?
  • Does fetch() reject the Promise on HTTP error statuses (like 404 or 500)?

advanced

  • How do you abort a fetch request?
  • What are CORS errors and how do they relate to fetch?

trick

  • Can you send cookies with a cross-origin fetch request?

Flash Cards

Question

How do you parse a JSON response?

Click to reveal answer
Answer

The fetch promise resolves to a Response object. You must call the `.json()` method on that response, which returns another Promise that resolves with the parsed JSON data.

Question

Does fetch() reject on HTTP errors like 404?

Click to reveal answer
Answer

No! A fetch() promise only rejects on network failures (like being offline). For HTTP errors (404, 500), it resolves normally, but the `response.ok` property will be false. You must manually check `response.ok`.

Question

How do you abort a fetch request?

Click to reveal answer
Answer

You use an `AbortController`. You pass its `signal` into the fetch options, and then call `controller.abort()` when you want to cancel the request.