Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

vor 3 Jahren
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # window.fetch polyfill
  2. The `fetch()` function is a Promise-based mechanism for programmatically making
  3. web requests in the browser. This project is a polyfill that implements a subset
  4. of the standard [Fetch specification][], enough to make `fetch` a viable
  5. replacement for most uses of XMLHttpRequest in traditional web applications.
  6. ## Table of Contents
  7. * [Read this first](#read-this-first)
  8. * [Installation](#installation)
  9. * [Usage](#usage)
  10. * [Importing](#importing)
  11. * [HTML](#html)
  12. * [JSON](#json)
  13. * [Response metadata](#response-metadata)
  14. * [Post form](#post-form)
  15. * [Post JSON](#post-json)
  16. * [File upload](#file-upload)
  17. * [Caveats](#caveats)
  18. * [Handling HTTP error statuses](#handling-http-error-statuses)
  19. * [Sending cookies](#sending-cookies)
  20. * [Receiving cookies](#receiving-cookies)
  21. * [Obtaining the Response URL](#obtaining-the-response-url)
  22. * [Aborting requests](#aborting-requests)
  23. * [Browser Support](#browser-support)
  24. ## Read this first
  25. * If you believe you found a bug with how `fetch` behaves in your browser,
  26. please **don't open an issue in this repository** unless you are testing in
  27. an old version of a browser that doesn't support `window.fetch` natively.
  28. This project is a _polyfill_, and since all modern browsers now implement the
  29. `fetch` function natively, **no code from this project** actually takes any
  30. effect there. See [Browser support](#browser-support) for detailed
  31. information.
  32. * If you have trouble **making a request to another domain** (a different
  33. subdomain or port number also constitutes another domain), please familiarize
  34. yourself with all the intricacies and limitations of [CORS][] requests.
  35. Because CORS requires participation of the server by implementing specific
  36. HTTP response headers, it is often nontrivial to set up or debug. CORS is
  37. exclusively handled by the browser's internal mechanisms which this polyfill
  38. cannot influence.
  39. * This project **doesn't work under Node.js environments**. It's meant for web
  40. browsers only. You should ensure that your application doesn't try to package
  41. and run this on the server.
  42. * If you have an idea for a new feature of `fetch`, **submit your feature
  43. requests** to the [specification's repository](https://github.com/whatwg/fetch/issues).
  44. We only add features and APIs that are part of the [Fetch specification][].
  45. ## Installation
  46. ```
  47. npm install whatwg-fetch --save
  48. ```
  49. You will also need a Promise polyfill for [older browsers](http://caniuse.com/#feat=promises).
  50. We recommend [taylorhakes/promise-polyfill](https://github.com/taylorhakes/promise-polyfill)
  51. for its small size and Promises/A+ compatibility.
  52. ## Usage
  53. For a more comprehensive API reference that this polyfill supports, refer to
  54. https://github.github.io/fetch/.
  55. ### Importing
  56. Importing will automatically polyfill `window.fetch` and related APIs:
  57. ```javascript
  58. import 'whatwg-fetch'
  59. window.fetch(...)
  60. ```
  61. If for some reason you need to access the polyfill implementation, it is
  62. available via exports:
  63. ```javascript
  64. import {fetch as fetchPolyfill} from 'whatwg-fetch'
  65. window.fetch(...) // use native browser version
  66. fetchPolyfill(...) // use polyfill implementation
  67. ```
  68. This approach can be used to, for example, use [abort
  69. functionality](#aborting-requests) in browsers that implement a native but
  70. outdated version of fetch that doesn't support aborting.
  71. For use with webpack, add this package in the `entry` configuration option
  72. before your application entry point:
  73. ```javascript
  74. entry: ['whatwg-fetch', ...]
  75. ```
  76. ### HTML
  77. ```javascript
  78. fetch('/users.html')
  79. .then(function(response) {
  80. return response.text()
  81. }).then(function(body) {
  82. document.body.innerHTML = body
  83. })
  84. ```
  85. ### JSON
  86. ```javascript
  87. fetch('/users.json')
  88. .then(function(response) {
  89. return response.json()
  90. }).then(function(json) {
  91. console.log('parsed json', json)
  92. }).catch(function(ex) {
  93. console.log('parsing failed', ex)
  94. })
  95. ```
  96. ### Response metadata
  97. ```javascript
  98. fetch('/users.json').then(function(response) {
  99. console.log(response.headers.get('Content-Type'))
  100. console.log(response.headers.get('Date'))
  101. console.log(response.status)
  102. console.log(response.statusText)
  103. })
  104. ```
  105. ### Post form
  106. ```javascript
  107. var form = document.querySelector('form')
  108. fetch('/users', {
  109. method: 'POST',
  110. body: new FormData(form)
  111. })
  112. ```
  113. ### Post JSON
  114. ```javascript
  115. fetch('/users', {
  116. method: 'POST',
  117. headers: {
  118. 'Content-Type': 'application/json'
  119. },
  120. body: JSON.stringify({
  121. name: 'Hubot',
  122. login: 'hubot',
  123. })
  124. })
  125. ```
  126. ### File upload
  127. ```javascript
  128. var input = document.querySelector('input[type="file"]')
  129. var data = new FormData()
  130. data.append('file', input.files[0])
  131. data.append('user', 'hubot')
  132. fetch('/avatars', {
  133. method: 'POST',
  134. body: data
  135. })
  136. ```
  137. ### Caveats
  138. * The Promise returned from `fetch()` **won't reject on HTTP error status**
  139. even if the response is an HTTP 404 or 500. Instead, it will resolve normally,
  140. and it will only reject on network failure or if anything prevented the
  141. request from completing.
  142. * For maximum browser compatibility when it comes to sending & receiving
  143. cookies, always supply the `credentials: 'same-origin'` option instead of
  144. relying on the default. See [Sending cookies](#sending-cookies).
  145. #### Handling HTTP error statuses
  146. To have `fetch` Promise reject on HTTP error statuses, i.e. on any non-2xx
  147. status, define a custom response handler:
  148. ```javascript
  149. function checkStatus(response) {
  150. if (response.status >= 200 && response.status < 300) {
  151. return response
  152. } else {
  153. var error = new Error(response.statusText)
  154. error.response = response
  155. throw error
  156. }
  157. }
  158. function parseJSON(response) {
  159. return response.json()
  160. }
  161. fetch('/users')
  162. .then(checkStatus)
  163. .then(parseJSON)
  164. .then(function(data) {
  165. console.log('request succeeded with JSON response', data)
  166. }).catch(function(error) {
  167. console.log('request failed', error)
  168. })
  169. ```
  170. #### Sending cookies
  171. For [CORS][] requests, use `credentials: 'include'` to allow sending credentials
  172. to other domains:
  173. ```javascript
  174. fetch('https://example.com:1234/users', {
  175. credentials: 'include'
  176. })
  177. ```
  178. To disable sending or receiving cookies for requests to any domain, including
  179. the current one, use the "omit" value:
  180. ```javascript
  181. fetch('/users', {
  182. credentials: 'omit'
  183. })
  184. ```
  185. The default value for `credentials` is "same-origin".
  186. The default for `credentials` wasn't always the same, though. The following
  187. versions of browsers implemented an older version of the fetch specification
  188. where the default was "omit":
  189. * Firefox 39-60
  190. * Chrome 42-67
  191. * Safari 10.1-11.1.2
  192. If you target these browsers, it's advisable to always specify `credentials:
  193. 'same-origin'` explicitly with all fetch requests instead of relying on the
  194. default:
  195. ```javascript
  196. fetch('/users', {
  197. credentials: 'same-origin'
  198. })
  199. ```
  200. #### Receiving cookies
  201. As with XMLHttpRequest, the `Set-Cookie` response header returned from the
  202. server is a [forbidden header name][] and therefore can't be programmatically
  203. read with `response.headers.get()`. Instead, it's the browser's responsibility
  204. to handle new cookies being set (if applicable to the current URL). Unless they
  205. are HTTP-only, new cookies will be available through `document.cookie`.
  206. #### Obtaining the Response URL
  207. Due to limitations of XMLHttpRequest, the `response.url` value might not be
  208. reliable after HTTP redirects on older browsers.
  209. The solution is to configure the server to set the response HTTP header
  210. `X-Request-URL` to the current URL after any redirect that might have happened.
  211. It should be safe to set it unconditionally.
  212. ``` ruby
  213. # Ruby on Rails controller example
  214. response.headers['X-Request-URL'] = request.url
  215. ```
  216. This server workaround is necessary if you need reliable `response.url` in
  217. Firefox < 32, Chrome < 37, Safari, or IE.
  218. #### Aborting requests
  219. This polyfill supports
  220. [the abortable fetch API](https://developers.google.com/web/updates/2017/09/abortable-fetch).
  221. However, aborting a fetch requires use of two additional DOM APIs:
  222. [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) and
  223. [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal).
  224. Typically, browsers that do not support fetch will also not support
  225. AbortController or AbortSignal. Consequently, you will need to include
  226. [an additional polyfill](https://github.com/mo/abortcontroller-polyfill#readme)
  227. for these APIs to abort fetches:
  228. ```js
  229. import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
  230. import {fetch} from 'whatwg-fetch'
  231. // use native browser implementation if it supports aborting
  232. const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch
  233. const controller = new AbortController()
  234. abortableFetch('/avatars', {
  235. signal: controller.signal
  236. }).catch(function(ex) {
  237. if (ex.name === 'AbortError') {
  238. console.log('request aborted')
  239. }
  240. })
  241. // some time later...
  242. controller.abort()
  243. ```
  244. ## Browser Support
  245. - Chrome
  246. - Firefox
  247. - Safari 6.1+
  248. - Internet Explorer 10+
  249. Note: modern browsers such as Chrome, Firefox, Microsoft Edge, and Safari contain native
  250. implementations of `window.fetch`, therefore the code from this polyfill doesn't
  251. have any effect on those browsers. If you believe you've encountered an error
  252. with how `window.fetch` is implemented in any of these browsers, you should file
  253. an issue with that browser vendor instead of this project.
  254. [fetch specification]: https://fetch.spec.whatwg.org
  255. [cors]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  256. "Cross-origin resource sharing"
  257. [csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
  258. "Cross-site request forgery"
  259. [forbidden header name]: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name