cheatsheets/js-fetch.md

92 lines
1.6 KiB
Markdown
Raw Permalink Normal View History

2016-06-02 23:01:18 +00:00
---
title: fetch()
category: JavaScript
2017-08-29 22:28:48 +00:00
weight: -3
2016-06-02 23:01:18 +00:00
---
2017-08-29 22:28:48 +00:00
### Fetch
{: .-prime}
2016-06-02 23:01:18 +00:00
```js
fetch('/data.json')
.then(response => response.json())
2017-08-29 22:28:48 +00:00
.then(data => {
console.log(data)
})
2016-06-02 23:01:18 +00:00
.catch(err => ...)
```
2017-08-29 22:28:48 +00:00
{: data-line="4"}
2016-06-02 23:01:18 +00:00
### Response
```js
fetch('/data.json')
.then(res => {
2016-10-09 15:45:09 +00:00
res.text() // response body (=> Promise)
res.json() // parse via JSON (=> Promise)
2016-06-02 23:01:18 +00:00
res.status //=> 200
res.statusText //=> 'OK'
res.redirected //=> false
res.ok //=> true
res.url //=> 'http://site.com/data.json'
2017-08-29 22:28:48 +00:00
res.type //=> 'basic'
// ('cors' 'default' 'error'
// 'opaque' 'opaqueredirect')
2016-06-02 23:01:18 +00:00
res.headers.get('Content-Type')
})
```
### Request options
```js
fetch('/data.json', {
method: 'post',
body: new FormData(form), // post body
body: JSON.stringify(...),
headers: {
'Accept': 'application/json'
2016-06-03 11:34:43 +00:00
},
credentials: 'same-origin', // send cookies
credentials: 'include', // send cookies, even in CORS
2016-06-02 23:01:18 +00:00
})
```
2016-06-03 11:34:43 +00:00
### Catching errors
```js
fetch('/data.json')
.then(checkStatus)
```
```js
function checkStatus (res) {
if (res.status >= 200 && res.status < 300) {
return res
} else {
let err = new Error(res.statusText)
2016-08-11 10:26:59 +00:00
err.response = res
2016-06-03 11:34:43 +00:00
throw err
}
}
```
2016-06-02 23:01:18 +00:00
2017-08-29 22:28:48 +00:00
Non-2xx responses are still successful requests. Use another function to turn them to errors.
### Using with node.js
2016-06-02 23:01:18 +00:00
```js
2017-08-29 22:28:48 +00:00
const fetch = require('isomorphic-fetch')
2016-06-02 23:01:18 +00:00
```
2017-08-29 22:28:48 +00:00
See: [isomorphic-fetch](https://npmjs.com/package/isomorphic-fetch) _(npmjs.com)_
2016-06-02 23:01:18 +00:00
## References
2017-08-29 22:28:48 +00:00
{: .-one-column}
2016-06-02 23:01:18 +00:00
- <https://fetch.spec.whatwg.org/>
- <https://www.npmjs.com/package/whatwg-fetch>