一、前言既然是h5的新方法,肯定有一些比较老的浏览器不支持。对于那些不支持该方法的浏览器,需要额外添加一个polyfill:[链接]:https://github。com/fis-components/whatwg-fetch2.用法ferch(fetching):HTML:fetch('/users.html')//这里返回一个Promise对象,不支持的浏览器需要对应的ployfill或者通过babel转码器转码后,执行.then(function(response){returnresponse.text()}).then(function(body){document.body.innerHTML=body})JSON:fetch('/users.json').then(function(response){returnresponse.json()}).then(function(json){console.log('parsedjson',json)}).catch(function(ex){console.log('parsingfailed',ex)})响应元数据: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)})Postform:varform=document.querySelector('form')fetch('/users',{method:'POST',body:newFormData(form)})PostJSON:fetch('/users',{方法:'POST',headers:{'Accept':'application/json','Content-Type':'application/json'},body:JSON.stringify({//这里是post请求的请求体name:'Hubot',login:'hubot',})})文件上传:varinput=document.querySelector('input[type="file"]')vardata=newFormData()data.append('file',input.files[0])//here获取选中的文件内容data.append('user','hubot')fetch('/avatars',{method:'POST',body:data})3.注意事项(一)与ajax的区别:1.fatch方法在取数据时即使是404或500错误也不会抛出错误,除非是网络错误或请求过程中断。不过当然是有解决办法的,下面是演示:functioncheckStatus(response){if(response.status>=200&&response.status<300){//判断response的状态码是否正常returnresponse//正常返回原始响应对象}else{varerror=newError(response.statusText)//异常抛出响应错误状态信息error.response=responsethrowerror}}functionparseJSON(response){returnresponse.json()}fetch('/users').then(checkStatus).then(parseJSON).then(function(data){console.log('requestsuccessedwithJSONresponse',data)}).catch(function(error){console.log('requestfailed',error)})2.一个很关键的问题,fetch方法不会发送cookies,这对于需要保持客户端和服务器之间的连接是致命的,因为服务器需要通过Cookies来标识某个session来维护session状态。发送cookie需要修改信息:fetch('/users',{credentials:'same-origin'//同域下发送cookie})fetch('https://segmentfault.com',{credentials:'include'//Sendcookiesacrossdomains})下图是跨域访问segment的结果Additional如果不出意外,请求的url和响应的url是一样的,但是如果你像redirect一样操作,响应.url可能不同。在XHR中,重定向后的response.url可能不准确。您需要设置:response.headers['X-Request-URL']=request.url适用于(Firefox<32、Chrome<37、Safari或IE。)
