Created
November 5, 2019 16:15
-
-
Save methbkts/fc42a17d6ffb8a23aa53bbd0ea952177 to your computer and use it in GitHub Desktop.
Sample to Fetch API
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
| fetch('some-url') | |
| .then(handleResponse) | |
| .then(data => console.log(data)) | |
| .catch(error => console.log(error)) | |
| function handleResponse (response) { | |
| let contentType = response.headers.get('content-type') | |
| if (contentType.includes('application/json')) { | |
| return handleJSONResponse(response) | |
| } else if (contentType.includes('text/html')) { | |
| return handleTextResponse(response) | |
| } else { | |
| // Other response types as necessary. | |
| throw new Error(`Sorry, content-type ${contentType} not supported`) | |
| } | |
| } | |
| function handleJSONResponse (response) { | |
| return response.json() | |
| .then(json => { | |
| if (response.ok) { | |
| return json | |
| } else { | |
| return Promise.reject(Object.assign({}, json, { | |
| status: response.status, | |
| statusText: response.statusText | |
| })) | |
| } | |
| }) | |
| } | |
| function handleTextResponse (response) { | |
| return response.text() | |
| .then(text => { | |
| if (response.ok) { | |
| return json | |
| } else { | |
| return Promise.reject({ | |
| status: response.status, | |
| statusText: response.statusText, | |
| err: text | |
| }) | |
| } | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment