Last active
May 18, 2017 13:49
-
-
Save gemmadlou/82601dd79398e8877ff3ba4fcfa12294 to your computer and use it in GitHub Desktop.
Fetch API js
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
| var create = function(name) { | |
| var data = JSON.stringify({ | |
| title: name, author: 'Gemma' | |
| }) | |
| fetch('http://localhost:3000/posts', { | |
| method: 'POST', | |
| body: data, | |
| headers: { | |
| 'Accept': 'application/json', | |
| 'Content-Type': 'application/json' | |
| } | |
| }) | |
| .then(function(res){ return res.json(); }) | |
| .then(function(response) { | |
| console.log(response); | |
| }).catch(function(err) { | |
| console.log(err) | |
| }) | |
| } | |
| var get = function(id) { | |
| var url = (typeof id == 'undefined') | |
| ? 'http://localhost:3000/posts' | |
| : 'http://localhost:3000/posts/' + id; | |
| fetch(url) | |
| .then((resp) => resp.json()) | |
| .then(function(response) { | |
| console.log(response) | |
| }) | |
| .catch(function(err) { | |
| console.log(err); | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment