- 使用fetch的优点
- 语法简洁,更加语义化
- 基于标准 Promise 实现,支持 async/await
- 同构方便,使用 isomorphic-fetch
为什么要用fetch
XMLHttpRequest 是一个设计粗糙的 API,不符合关注分离(Separation of Concerns)的原则,配置和调用方式非常混乱,而且基于事件的异步模型写起来也没有现代的 Promise,generator/yield,async/await 友好。
fetch就是为了解决xhr的问题的
使用xhr传递一个json请求 ,
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function() {
console.log(xhr.response);
};
xhr.onerror = function() {
console.log("Oops, error");
};
xhr.send();
使用fetch来传递请求
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
});
与ajax相比
- ajax只能实现同源请求,fetch可实现跨域请求;
- Fetch代码很像jQuery中的ajax,但是两者是不同的,fetch是原生的js,而jQuery中的ajax是库封装的;
- ajax几乎所有的主流浏览器都支持,但fetch由于目前并没有被列入标准,只有像firefox最新版,chrome最新版,以及IE10+等以上才支持;
一个完整的post请求和响应过程
var url = "/fetch";
fetch(url,{
method:"post",
headers:{
"Content-type":"application/x-www-form-urlencoded"
},
body:"name=luwenjing&age=22"
})
.then(function (response){
if (response.status == 200){
return response;
}
})
.then(function (data) {
return data.text();
})
.then(function(text){
console.log("请求成功,响应数据为:",text);
})
.catch(function(err){
console.log("Fetch错误:"+err);
});
与异步编程相关的ES7的Async/Await