// 1) set headers
var headers = new Headers({
'Content-Type': 'text/plain',
'X-My-Custom-Header': 'CustomValue'
});
// headers.append('Content-Type', 'text/plain');
// headers.has('Content-Type'); // true
// headers.get('Content-Type'); // "text/plain"
// headers.set('Content-Type', 'application/json');
// headers.delete('X-My-Custom-Header');
// 2) set request
var request = new Request('https://davidwalsh.name/users.json', {
method: 'POST', // GET, POST, PUT, DELETE, HEAD
mode: 'cors', // cors, no-cors, same-origin
redirect: 'follow', // follow, error, manual
headers: new Headers({
'Content-Type': 'text/plain'
})
//url : URL of the request
//headers : associated Headers object
//referrer : referrer of the request
//credentials : should cookies go with the request? omit, same-origin
//integrity - subresource integrity value
//cache - cache mode (default, reload, no-cache)
});
// 3) fetch! --fetch API uses JavaScript Promises to handle results/callbacks:
fetch(request).then(function(response) {
// handle response
}).catch(function(err) {
// Error
});
// You can chain promises for more "advanced" handling: for example, if you make a request for JSON, the resulting callback data has a json method for converting the raw data to a JavaScript object
fetch(request).then(function(response) {
return response.json(); //shortcut for JSON.parse(jsonString)
}).then(function(j) {
// Yay, 'j' is a JavaScript object
console.log(j);
}).catch(function(err) {
// Error
});
// POSTing JSON data:
fetch('https://davidwalsh.name/submit-json', {
method: 'post',
body: JSON.stringify({
email: document.getElementById('email').value
answer: document.getElementById('answer').value
})
});
// POSTing Form Data
fetch('https://davidwalsh.name/submit', {
method: 'post',
body: new FormData(document.getElementById('comment-form'))
});