h5的fetch方法_关于h5中的fetch方法解读

本文介绍了HTML5的fetch方法,包括其用法、注意事项和与AJAX的区别。fetch返回Promise对象,支持GET、POST等多种请求类型,并演示了处理响应状态和发送cookie的方法。同时,文章提到了fetch在处理错误和保持会话状态方面的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 前言

既然是h5的新方法,肯定就有一些比较older的浏览器不支持了,对于那些不支持此方法的

浏览器就需要额外的添加一个polyfill:

[链接]: https://github.com/fis-components/whatwg-fetch

2. 用法

ferch(抓取) :

HTML:

fetch('/users.html') //这里返回的是一个Promise对象,不支持的浏览器需要相应的ployfill或通过babel等转码器转码后在执行

.then(function(response) {

return response.text()})

.then(function(body) {

document.body.innerHTML = body

})

JSON :

fetch('/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 metadata :

fetch('/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 form:

var form = document.querySelector('form')

fetch('/users', {

method: 'POST',

body: new FormData(form)

})

Post JSON:

fetch('/users', {

method: 'POST',

headers: {

'Accept': 'application/json',

'Content-Type': 'application/json'

},

body: JSON.stringify({ //这里是post请求的请求体

name: 'Hubot',

login: 'hubot',

})

})

File upload:

var 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

})

3. 注意事项

(1)和ajax的不同点:

1. fatch方法抓取数据时不会抛出错误即使是404或500错误,除非是网络错误或者请求

过程中被打断.但当然有解决方法啦,下面是demonstration:

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)

})

2.一个很关键的问题,fetch方法不会发送cookie,这对于需要保持客户端和服务器端

常连接就很致命了,因为服务器端需要通过cookie来识别某一个session来达到保持会

话状态.要想发送cookie需要修改一下信息:

fetch('/users', {

credentials: 'same-origin' //同域下发送cookie

})

fetch('https://segmentfault.com', {

credentials: 'include' //跨域下发送cookie

})

下图是跨域访问segment的结果

Additional

如果不出意外的话,请求的url和响应的url是相同的,但是如果像redirect这种操作的

话response.url可能就会不一样.在XHR时,redirect后的response.url可能就不太准

确了,需要设置下:response.headers['X-Request-URL'] = request.url

适用于( Firefox < 32, Chrome < 37, Safari, or IE.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值