在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:github/fetch开源软件地址:https://github.com/github/fetch开源编程语言:JavaScript 99.4%开源软件介绍:window.fetch polyfillThe Table of ContentsRead this first
Installation
As an alternative to using npm, you can obtain You will also need a Promise polyfill for older browsers. We recommend taylorhakes/promise-polyfill for its small size and Promises/A+ compatibility. UsageFor a more comprehensive API reference that this polyfill supports, refer to https://github.github.io/fetch/. ImportingImporting will automatically polyfill import 'whatwg-fetch'
window.fetch(...) If for some reason you need to access the polyfill implementation, it is available via exports: import {fetch as fetchPolyfill} from 'whatwg-fetch'
window.fetch(...) // use native browser version
fetchPolyfill(...) // use polyfill implementation This approach can be used to, for example, use abort functionality in browsers that implement a native but outdated version of fetch that doesn't support aborting. For use with webpack, add this package in the entry: ['whatwg-fetch', ...] HTMLfetch('/users.html')
.then(function(response) {
return response.text()
}).then(function(body) {
document.body.innerHTML = body
}) JSONfetch('/users.json')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
}) Response metadatafetch('/users.json').then(function(response) {
console.log(response.headers.get('Content-Type'))
console.log(response.headers.get('Date'))
console.log(response.status)
console.log(response.statusText)
}) Post formvar form = document.querySelector('form')
fetch('/users', {
method: 'POST',
body: new FormData(form)
}) Post JSONfetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
}) File uploadvar input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
}) Caveats
Handling HTTP error statusesTo have function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
}
function parseJSON(response) {
return response.json()
}
fetch('/users')
.then(checkStatus)
.then(parseJSON)
.then(function(data) {
console.log('request succeeded with JSON response', data)
}).catch(function(error) {
console.log('request failed', error)
}) Sending cookiesFor CORS requests, use fetch('https://example.com:1234/users', {
credentials: 'include'
}) The default value for The default for
If you target these browsers, it's advisable to always specify fetch('/users', {
credentials: 'same-origin'
}) Note: due to limitations of
XMLHttpRequest,
using Receiving cookiesAs with XMLHttpRequest, the Redirect modesThe Fetch specification defines these values for the Due to limitations of XMLHttpRequest, only the "follow" mode is available in browsers where this polyfill is active. Obtaining the Response URLDue to limitations of XMLHttpRequest, the The solution is to configure the server to set the response HTTP header
# Ruby on Rails controller example
response.headers['X-Request-URL'] = request.url This server workaround is necessary if you need reliable Aborting requestsThis polyfill supports the abortable fetch API. However, aborting a fetch requires use of two additional DOM APIs: AbortController and AbortSignal. Typically, browsers that do not support fetch will also not support AbortController or AbortSignal. Consequently, you will need to include an additional polyfill for these APIs to abort fetches: import 'yet-another-abortcontroller-polyfill'
import {fetch} from 'whatwg-fetch'
// use native browser implementation if it supports aborting
const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch
const controller = new AbortController()
abortableFetch('/avatars', {
signal: controller.signal
}).catch(function(ex) {
if (ex.name === 'AbortError') {
console.log('request aborted')
}
})
// some time later...
controller.abort() Browser Support
Note: modern browsers such as Chrome, Firefox, Microsoft Edge, and Safari contain native
implementations of |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论