Last active
March 30, 2019 09:06
-
-
Save potikanond/dd06d5f84d117426e887daabbf26c908 to your computer and use it in GitHub Desktop.
JavaScript "Fetch API" tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* References: | |
| https://developers.google.com/web/updates/2015/03/introduction-to-fetch | |
| https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data | |
| https://medium.freecodecamp.org/a-practical-es6-guide-on-how-to-perform-http-requests-using-the-fetch-api-594c3d91a547 | |
| */ | |
| /* Making Simple GET Request: | |
| // fetch(url) // Call the fetch function passing the url of the API as a parameter | |
| // .then(function() { | |
| // // Your code for handling the data you get from the API | |
| // }) | |
| // .catch(function() { | |
| // // This is where you run code if the server returns any errors | |
| */ }); | |
| /* | |
| clone() - As the method implies this method creates a clone of the response. | |
| redirect() - This method creates a new response but with a different URL. | |
| arrayBuffer() - In here we return a promise that resolves with an ArrayBuffer. | |
| formData() - Also returns a promise but one that resolves with FormData object. | |
| blob() - This is one resolves with a Blob. | |
| text() - In this case it resolves with a string. | |
| json() - Lastly we have the method to that resolves the promise with JSON. | |
| */ | |
| // example1: | |
| fetch('https://jsonplaceholder.typicode.com/todos/1') // make a request | |
| .then(response => response.json()) // handle data as JSON | |
| .then(data => console.log(JSON.stringify(data))) // get 'data' and process | |
| .then(data => { // do something else | |
| console.log('done'); | |
| }); | |
| // example2: | |
| fetch('https://jsonplaceholder.typicode.com/users').then( | |
| (res) => { | |
| console.log(res.headers.get('content-type')); | |
| console.log(res.headers.get('date')); | |
| console.log(res.status); | |
| console.log(res.statusText); | |
| console.log(res.url); | |
| res.json().then( | |
| (data) => { | |
| console.log(data); | |
| } | |
| ); | |
| } | |
| ).catch( | |
| (err) => { | |
| console.log(err); | |
| } | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment