Skip to content

Instantly share code, notes, and snippets.

@gemmadlou
Last active May 18, 2017 13:49
Show Gist options
  • Select an option

  • Save gemmadlou/82601dd79398e8877ff3ba4fcfa12294 to your computer and use it in GitHub Desktop.

Select an option

Save gemmadlou/82601dd79398e8877ff3ba4fcfa12294 to your computer and use it in GitHub Desktop.
Fetch API js
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