1、fetchjavascript
fetch是一种XMLHttpRequest的一种替代方案,在工做当中除了用ajax获取后台数据外咱们还可使用fetch、axios来替代ajaxjava
2、安装node
执行npm install whatwg-fetch --save便可安装。ios
为了兼容老版本浏览器,还须要安装npm install es6-promise --savees6
3、fetch的基本使用ajax
npm install whatwg-fetch --savenpm install es6-promise --saveimport 'es6-promise'import 'whatwg-fetch'
fetch(url,options).then((res)=>{ console.log(res);},function(err){ console.log(err)})
说明:npm
一、fetch的返回值是一个promise对象json
二、optionsaxios
method:HTTP请求方式,默认是GETapi
body:请求的参数
fetch('/xxx', {
method: 'post',
body:'username=zhangsan&age=17'
});
headers:HTTP请求头
由于通常使用JSON数据格式,因此设置ContentType为application/json
credentials:默认为omit,忽略的意思,也就是不带cookie还有两个参数,same-origin,意思就是同源请求带cookie;include,表示不管跨域仍是同源请求都会带cookie
三、在.then里面第一个回调函数中处理response
status(number): HTTP返回的状态码,范围在100-599之间
statusText(String): 服务器返回的状态文字描述
headers: HTTP请求返回头
body: 返回体,这里有处理返回体的一些方法
text(): 将返回体处理成字符串类型
json(): 返回结果和 JSON.parse(responseText)同样
blob(): 返回一个Blob,Blob对象是一个不可更改的类文件的二进制数据
若是请求一个XML格式文件,则调用response.text。若是请求图片,使用response.blob方法
注意:
cookie传递
必须在header参数里面加上credentials: 'include',才会如xhr同样将当前cookies带到请求中去
4、get、post请求方式
一、get
var result = fetch('url', { credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', }, });
二、post
var result = fetch('/api/post', { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/x-www-form-urlencoded' }, // 注意 post 时候参数的形式 body: "a=100&b=200" });
5、封装get和post方法
一、http.get()
import 'es6-promise'import 'whatwg-fetch'
export default (url)=>({ var result = fetch(url, { credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', }, }) .then(res=>res.json()); return result})
二、http.post
import 'es6-promise'import 'whatwg-fetch'import qs from 'qs';export default (url,data)=>({ var result = fetch(url, { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/x-www-form-urlencoded' }, // 注意 post 时候参数的形式 body: qs(data) }) .then(res=>res.json()) return result;})
6、fetch与axios的区别
axios("http://xxx/xxx.json?a=123'").then((res)=>{ console.log(res)//这里的r是响应结果})
fetch("http://www.baidu.com").then((res)=>{ console.log(res);//是一个综合各类方法的对象,并非请求的数据})
fetch返回的是一个未处理的方法集合,咱们能够经过这些方法获得咱们想要的数据类型。若是咱们想要json格式,就执行response.json(),若是咱们想要字符串就response.text()
axios
一、从浏览器中建立 XMLHttpRequest
二、从 node.js 发出 http 请求
三、支持 Promise API
四、拦截请求和响应
五、转换请求和响应数据
六、自动转换JSON数据
七、客户端支持防止CSRF/XSRF
fetch:
符合关注分离,没有将输入、输出和用事件来跟踪的状态混杂在一个对象里
更加底层,提供的API丰富(request, response)
脱离了XHR,是ES规范里新的实现方式
一、fetchtch只对网络请求报错,对400,500都当作成功的请求,须要封装去处理
二、fetch默认不会带cookie,须要添加配置项
三、fetch不支持abort,不支持超时控制,使用setTimeout及Promise.reject的实
现的超时控制并不能阻止请求过程继续在后台运行,形成了量的浪费
四、fetch没有办法原生监测请求的进度,而XHR能够