How do you make an HTTP request using the Fetch API?
Topics
JavaScriptNetworking
TL;DR
To make an HTTP request, call fetch(), which returns a promise for a Response. Fetch rejects for failures such as malformed URLs, network errors, CORS failures, and aborts (not for HTTP statuses such as 404 or 500) so check response.ok (or response.status) before reading the body.
fetch() has two asynchronous stages: obtaining a response and, usually, consuming its body.
Fetch request and response handling
fetch() does not reject merely because the server returns an HTTP error status, so status handling must be explicit.
Making an HTTP request using the Fetch API
Basic GET request
To make a basic GET request, you can use the fetch function with the URL of the resource you want to fetch. The fetch function returns a promise that resolves to the Response object representing the response to the request.
To make a POST request, you need to pass an options object as the second argument to fetch. This object can include the HTTP method, headers, and body of the request.
Use .catch() or try...catch for rejected promises. Because an HTTP error response still fulfills the Fetch promise, explicitly check response.ok (or handle the status codes your application expects).
fetch('https://jsonplaceholder.tyicode.com/posts/1/comments') // Typo in the URL