Skip to content

Instantly share code, notes, and snippets.

@frankstepanski
Created January 30, 2021 06:14
Show Gist options
  • Save frankstepanski/7cfe0d4d8068e39bc3507d82a2d5a3ee to your computer and use it in GitHub Desktop.
Save frankstepanski/7cfe0d4d8068e39bc3507d82a2d5a3ee to your computer and use it in GitHub Desktop.
Using fetch API
// 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