Browser - Web API - Fetch function
Table of Contents
1 - About
The fetch function is part of the web api function and is a AJAX call. It's one of the possibilities to fetch a resource.
The fetch function returns a promise as response.
The Fetch Standard defines the fetch() JavaScript API
It exposes most of the networking functionality at a low level of abstraction.
2 - Articles Related
3 - Syntax
fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, PUT, DELETE, etc.
mode: 'cors', // no-cors, *same-origin
redirect: 'follow', // *manual, error
referrer: 'no-referrer', // *client
credentials: 'same-origin'
})
.then(
function(response) {
if (response.status !== 200) {
console.log('Bad request, status Code is: ' + response.status);
return;
}
// Response properties
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));
console.log(response.status);
console.log(response.statusText);
console.log(response.type); // "basic", "cors" or "opaque"
console.log(response.url);
// Parses response data to JSON
// * response.json()
// * response.text()
// are promise, you need to pass them to a callback to get the value
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error', err);
}
The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.
4 - Request
The request is specified in the first block of the fetch statement and has properties.
4.1 - Credentials
Credentials are HTTP cookies, TLS client certificates, and authentication entries (for HTTP authentication). For CORS requests, use the “include” value to allow sending credentials to other domains:
4.2 - Mode
Mode possible values:
- no-cors (Default) (ie no-cors) (discouraged - unsafe): Restricts requests to using:
- CORS-safelisted method (`GET`, `HEAD`, or `POST`)
- same-origin: Used to ensure requests are made to same-origin URLs
- cors: Makes the request a CORS request.
- navigate: This is a special mode used only when navigating between documents.
- websocket: This is a special mode used only when establishing a WebSocket connection.
5 - Management
5.1 - Polyfill
5.2 - See
6 - Example
6.1 - Get
response.text() return a promise, you need to resolve it
fetch('https://gerardnico.com/doc/api/weather', {
method: 'GET', // *GET, PUT, DELETE, etc.
})
.then(function(response) {
console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
// Response text is a promise, you need to pass it to a callback to resolve it
response.text().then(function(data) {
console.log(data);
});
})
6.2 - Post
var data = { name: "Nicolas", age: 46, city: "Oegstgeest" }
var formData = new URLSearchParams();
formData.append('json', JSON.stringify(data));
fetch('aURL', {
body: formData,
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
method: 'POST',
mode: 'no-cors',
redirect: 'follow',
credentials: 'same-origin'
})
.then(response => console.log(response))
or
fetch(url, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'foo=bar&lorem=ipsum'
})
.then(response => response.json())
.then(function (data) {
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
console.log('Request failed', error);
});
6.3 - More
7 - Wrapper Library
7.1 - isomorphic-unfetch
- https://github.com/developit/unfetch - unfetch is a wrapper around the fetch api that works in the server and client side.
npm install --save isomorphic-unfetch