Created
December 11, 2017 12:30
-
-
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)
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
{ | |
"posts": [ | |
{ "id": 1, "title": "json-server", "author": "typicode" } | |
], | |
"comments": [ | |
{ "id": 1, "body": "some comment", "postId": 1 } | |
], | |
"profile": { "name": "typicode" } | |
} |
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
(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