Fetch Api
May 24, 2020Fetch Api is used to make network requests to the server.
For example, we can use a network request to:
- Submit an order,
- Load user information,
- Receive latest updates from the server,
- …etc.
Basic Syntax of Fetch
let promise = fetch(url, [options])
Fetch method has two parameters:
- url: Server’s address to whom you want to make network requests.
- options: These are optional parameters where you can pass headers, methods (Example: GET, POST) etc…
Note: Without options fetch api will be of type GET Method which will only download the contents from server in the form of json or text.
When a fetch method is called then first it will return a promise which resolves into a object of built in Response
Class as soon as server responds with headers.
Example:
let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
// get the response body (the method explained below)
let json = await response.json();
} else {
alert("HTTP-Error: " + response.status);
}
Second, to get the response body, we need to use an additional method call.
Response provides multiple promise-based methods to access the body in various formats:
- response.text() – read the response and return as text,
- response.json() – parse the response as JSON,
- response.formData() – return the response as FormData object (explained in the next chapter),
- response.blob() – return the response as Blob (binary data with type),
- response.arrayBuffer() – return the response as ArrayBuffer (low-level representaion of * binary data),
- additionally, response.body is a ReadableStream object, it allows you to read the body chunk-by-chunk, we’ll see an example later.