web 3d图形渲染器
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.

354 lines
11 KiB

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