Skip to content

Instantly share code, notes, and snippets.

@helton
Created December 11, 2017 12:30
Show Gist options
  • Save helton/b1fe892d6e47af5f8063a6e6cade3faf to your computer and use it in GitHub Desktop.
Save helton/b1fe892d6e47af5f8063a6e6cade3faf to your computer and use it in GitHub Desktop.
Fetch API Test - POST (make sure you start json-server => https://github.com/typicode/json-server)
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
(function() {
function post(path,payload) {
const request = new Request(`http://localhost:3000/${path}`, {
headers: new Headers({
'Content-Type': 'application/json'
})
});
console.log('Posting request...');
fetch(request, {
method: 'POST',
body: JSON.stringify(payload)
}).then(function(response) {
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
}).then(function(data) {
console.log('POST submitted successfully');
console.log('Response:', JSON.stringify(data));
});
}
const id = new Date().getTime();
post('comments', {
id,
body: "It's working!",
postId: id
});
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment