# Fetch API Examples
# ⚠️ _2019-2020:_ [See more examples and updates on my article
here!]([Link]
> [Link]
=====================================================
=====================================================
=====================================================
=====================================================
## ~DEPRECATED BELOW~
## Table of Contents
1. GET Requests
1. [Easy: Get JSON from a URL](#easy-get-json-from-a-url)
1. [Intermediate: Custom headers](#intermediate-custom-headers)
1. [Advanced: CORS example](#advanced-cors-example)
1. POST/PUT Requests
1. [Easy: Posting JSON](#easy-posting-json)
1. [Intermediate: Posting an HTML `<form>`](#intermediate-posting-an-html-form)
1. [Intermediate: Form encoded data](#intermediate-form-encoded-data)
1. [Advanced: Uploading Files](#advanced-uploading-files)
1. [Advanced: Uploading Multiple Files](#advanced-uploading-multiple-files)
1. Bonus
1. Dependant Fetch Requests
1. Concurrent Downloads
## GET Requests
### Easy: Get JSON from a URL
```js
fetch('[Link]
.then(response => [Link]())
.then(data => {
[Link](data) // Prints result from `[Link]()` in getRequest
})
.catch(error => [Link](error))
```
### Intermediate: Custom headers
```js
fetch('[Link] {
headers: new Headers({
'User-agent': 'Mozilla/4.0 Custom User Agent'
})
})
.then(response => [Link]())
.then(data => {
[Link](data)
})
.catch(error => [Link](error))
```
### Advanced: CORS example
CORS is primarily checked at the server - so make sure your configuration is
correct on the server-side.
The `credentials` option controls if your cookies are automatically included.
```js
fetch('[Link] {
credentials: 'include', // Useful for including session ID (and, IIRC,
authorization headers)
})
.then(response => [Link]())
.then(data => {
[Link](data) // Prints result from `[Link]()`
})
.catch(error => [Link](error))
```
## POST/PUT Requests
### Easy: Posting JSON
```js
postRequest('[Link] {user: 'Dan'})
.then(data => [Link](data)) // Result from the `[Link]()` call
.catch(error => [Link](error))
function postRequest(url, data) {
return fetch(url, {
credentials: 'same-origin', // 'include', default: 'omit'
method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
body: [Link](data), // Coordinate the body type with 'Content-Type'
headers: new Headers({
'Content-Type': 'application/json'
}),
})
.then(response => [Link]())
}
```
### Intermediate: Posting an HTML `<form>`
```js
postForm('[Link]
.then(data => [Link](data))
.catch(error => [Link](error))
function postForm(url) {
const formData = new FormData([Link]('[Link]-user'))
return fetch(url, {
method: 'POST', // or 'PUT'
body: formData // a FormData will automatically set the 'Content-Type'
})
.then(response => [Link]())
}
```
### Intermediate: Form encoded data
To post data with a Content-Type of `application/x-www-form-urlencoded` we will use
`URLSearchParams` to encode the data like a query string.
For example, `new URLSearchParams({a: 1, b: 2})` yields `a=1&b=2`.
```js
postFormData('[Link] {user: 'Mary'})
.then(data => [Link](data))
.catch(error => [Link](error))
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 => [Link]())
}
```
### Advanced: Uploading files
```js
postFile('[Link] 'input[type="file"].avatar')
.then(data => [Link](data))
.catch(error => [Link](error))
function postFile(url, fileSelector) {
const formData = new FormData()
const fileField = [Link](fileSelector)
[Link]('username', 'abc123')
[Link]('avatar', [Link][0])
return fetch(url, {
method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
body: formData // Coordinate the body type with 'Content-Type'
})
.then(response => [Link]())
}
```
### Advanced: Uploading multiple files
Setup a file upload element with the `multiple` attribute:
```html
<input type='file' multiple class='files' name='files' />
```
Then use with something like:
```js
postFile('[Link] 'input[type="file"].files')
.then(data => [Link](data))
.catch(error => [Link](error))
function postFile(url, fileSelector) {
const formData = new FormData()
const fileFields = [Link](fileSelector)
// Add all files to formData
[Link]([Link], f => [Link]('files', f))
// Alternatively for PHP peeps, use `files[]` for the name to support arrays
// [Link]([Link], f => [Link]('files[]',
f))
return fetch(url, {
method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
body: formData // Coordinate the body type with 'Content-Type'
})
.then(response => [Link]())
}
```