JavaScript Fetch API
JS
S
JavaScriptAlternative and improvement over XMLHttpRequest. The Fetch API provides a more powerful and flexible feature set. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API Availability: LS across modern browsers.
1// Simple example
2if(window.fetch){
3 fetch(document.location.href)
4 .then(resp => {
5 const csp = resp.headers.get('Content-Security-Policy');
6 console.log(resp.headers);
7 });
8}
9
10// Another Example
11var opts = {
12 method: "post",
13 headers: {
14 "Content-Type": "application/json",
15 "Authorization": "Bearer " + (user ? user.access_token : "")
16 },
17 body: JSON.stringify({ query: '{ loggedUsers { id name } }' })
18};
19
20fetch(url, opts)
21 .then(res => {
22 if (res.status !== 200) {
23 throw new Error(res.status)
24 }
25 return res.json()
26 })
27 .then(log)
28 .catch(log);Created on 1/12/2018