You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

349 lines
11 KiB

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