Lesson 15 of 28

In progress

Course progress

JavaScript

fetch: talking to a server

Send GET and POST requests, check the status before parsing, and show loading and error states that make sense.

fetch is the browser’s built-in way to make HTTP requests. It returns a promise, so you will also meet await, response.json() and the difference between a network failure and an HTTP error.

What you will learn

  • Send a GET request and read the JSON response.
  • Check response.ok before parsing.
  • Send data with POST and show loading and error states.

A GET request

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

Two awaits: the first waits for the response headers, the second waits for the body. response.json() parses the body as JSON and returns a promise. Calling response.json() twice fails, because the body can only be read once.

In this runner the request goes to a public test API. If the network is unavailable, the call rejects and the error is visible in the console, which is itself a useful demonstration.

Check the status

fetch rejects only when the request cannot be made: no network, a blocked domain, a CORS failure. It resolves for 404 and 500, because those are valid HTTP responses.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

response.ok is true for statuses 200 to 299. Throwing turns an HTTP failure into a rejected promise, so a single catch handles both kinds of failure. Without the check, parsing an error page as JSON throws a confusing SyntaxError instead.

response.status and response.statusText are useful for messages and logs. Do not show the raw text to users; map common codes to a sentence.

POST with JSON

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

The body must be a string, so objects go through JSON.stringify. The Content-Type header tells the server how to parse it. For form uploads, pass a FormData object as the body and let the browser set the header, including the multipart boundary.

credentials: "include" sends cookies cross-origin, which most APIs require explicitly. Do not enable it casually; it broadens what a page can do with a signed-in session.

Headers and CORS

Request headers describe what you send and what you accept. Accept: application/json states the expected response; Content-Type states what the body contains. A server may also require an API key or an authorization header, which belongs in server-side code whenever possible, because anything in the browser is visible.

CORS is the browser’s rule for cross-origin reads. The server must send Access-Control-Allow-Origin for the requesting origin. When it does not, the request may still reach the server, but the browser hides the response and the promise rejects with a network error. A CORS failure is a server configuration issue; no client header can fix it.

Loading, success and failure

A request is a state machine, and the interface should show which state it is in.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

The user sees a loading state, then either content or a plain-language error. The technical detail goes to the console. That split is the whole pattern, and it is worth applying consistently.

Cancelling and timeouts

A request that never resolves should not leave a spinner forever. AbortController cancels a fetch and rejects its promise with an AbortError.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

Clearing the timer in finally prevents a stray abort after a fast response. Check for error.name === "AbortError" when you need to distinguish cancellation from a network failure.

Forgetting await response.json() and logging the promise instead of the data is the most common fetch confusion. response.json() returns a promise because reading the body is asynchronous. Also remember CORS: a browser blocks reading a cross-origin response unless the server sends the right headers, and no client code can override that.

Write loadTitle(url, element) that fetches JSON, sets the element’s text to the title, and shows "Unavailable" with a console warning on any failure. Add a loading message before the request.

Show solution
JavaScript
Editable. Runs in your browser.





Press Run to see the output.

The three states are explicit: loading, success and failure. The catch covers HTTP errors, network errors and parse errors, which all end with the same user-facing sentence.

Recap

  • fetch resolves for HTTP errors, so check response.ok and throw deliberately.
  • Read the body once with response.json(); POST sends a stringified body and a content type.
  • Show loading, success and failure states, and use AbortController for timeouts.

Next, you will see what a promise is underneath await, and how to wait for several at once.

Why does fetch not reject on a 404?
Because the request succeeded: the server answered. The status describes the answer, not the transport, so checking it is your job.
How do I send credentials?
Use `credentials: “include”` and configure CORS on the server to allow the origin. Cookies are not sent cross-origin by default.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.