OSDN Git Service

Regular updates
[twpd/master.git] / js-fetch.md
1 ---
2 title: fetch()
3 category: JavaScript
4 layout: 2017/sheet
5 weight: -3
6 ---
7
8 ### Fetch
9 {: .-prime}
10
11 ```js
12 fetch('/data.json')
13   .then(response => response.json())
14   .then(data => {
15     console.log(data)
16   })
17   .catch(err => ...)
18 ```
19 {: data-line="4"}
20
21 ### Response
22
23 ```js
24 fetch('/data.json')
25 .then(res => {
26   res.text()       // response body (=> Promise)
27   res.json()       // parse via JSON (=> Promise)
28   res.status       //=> 200
29   res.statusText   //=> 'OK'
30   res.redirected   //=> false
31   res.ok           //=> true
32   res.url          //=> 'http://site.com/data.json'
33   res.type         //=> 'basic'
34                    //   ('cors' 'default' 'error'
35                    //    'opaque' 'opaqueredirect')
36
37   res.headers.get('Content-Type')
38 })
39 ```
40
41 ### Request options
42
43 ```js
44 fetch('/data.json', {
45   method: 'post',
46   body: new FormData(form), // post body
47   body: JSON.stringify(...),
48
49   headers: {
50     'Accept': 'application/json'
51   },
52
53   credentials: 'same-origin', // send cookies
54   credentials: 'include',     // send cookies, even in CORS
55
56 })
57 ```
58
59 ### Catching errors
60
61 ```js
62 fetch('/data.json')
63   .then(checkStatus)
64 ```
65
66 ```js
67 function checkStatus (res) {
68   if (res.status >= 200 && res.status < 300) {
69     return res
70   } else {
71     let err = new Error(res.statusText)
72     err.response = res
73     throw err
74   }
75 }
76 ```
77
78 Non-2xx responses are still successful requests. Use another function to turn them to errors.
79
80 ### Using with node.js
81
82 ```js
83 const fetch = require('isomorphic-fetch')
84 ```
85
86 See: [isomorphic-fetch](https://npmjs.com/package/isomorphic-fetch) _(npmjs.com)_
87
88 ## References
89 {: .-one-column}
90
91 - <https://fetch.spec.whatwg.org/>
92 - <https://www.npmjs.com/package/whatwg-fetch>