Created
January 30, 2021 06:14
-
-
Save frankstepanski/7cfe0d4d8068e39bc3507d82a2d5a3ee to your computer and use it in GitHub Desktop.
Using fetch API
This file contains 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
// GET: | |
// no custom headers | |
fetch(url) | |
.then(response => response.json()) | |
.then(data => { | |
console.log(data) | |
}) | |
.catch(error => console.error(error)) | |
// custom headers: | |
fetch(url', { | |
headers: new Headers({ | |
'User-agent': 'Mozilla/4.0 Custom User Agent' | |
}) | |
}) | |
.then(response => response.json()) | |
.then(data => { | |
console.log(data) | |
}) | |
.catch(error => console.error(error)) | |
// CORS | |
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials | |
fetch('https://api.github.com/orgs/nodejs', { | |
credentials: 'include', // Useful for including session ID (and, IIRC, authorization headers) | |
}) | |
.then(response => response.json()) | |
.then(data => { | |
console.log(data) // Prints result from `response.json()` | |
}) | |
.catch(error => console.error(error)) | |
// POST: | |
// JSON | |
postRequest('http://example.com/api/v1/users', {user: 'Tom'}) | |
.then(data => console.log(data)) // Result from the `response.json()` call | |
function postRequest(url, data) { | |
return fetch(url, { | |
credentials: 'same-origin', // 'include', default: 'omit' | |
method: 'POST', // 'GET', 'PUT', 'DELETE', etc. | |
body: JSON.stringify(data), // Use correct payload (matching 'Content-Type') | |
headers: { 'Content-Type': 'application/json' }, | |
}) | |
.then(response => response.json()) | |
.catch(error => console.error(error)) | |
} | |
// Form (encoded) data: | |
postFormData('http://example.com/api/v1/users', {user: 'Tom'}) | |
.then(data => console.log(data)) | |
function postFormData(url, data) { | |
return fetch(url, { | |
method: 'POST', // 'GET', 'PUT', 'DELETE', etc. | |
body: new URLSearchParams(data), | |
headers: new Headers({ | |
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' | |
}) | |
}) | |
.then(response => response.json()) | |
.catch(error => console.error(error)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment