关于fetch
简单的说 fetch是一种ajax的升级版替代方案,ajax的实现就是依赖xmlhttpRequest对象,而fetch是window对象的一个方法
并且实现了es6的promise来处理回调。
fetch的使用
fetch目前除了老版本浏览器之外支持的还可以,查看fetch的支持情况
老版本浏览器也可以通过引入第三方的polyfill 来支持 whatwg-fetch
fetch的具体使用
get方法
fetch('http://localhost:8080/projectList?name=123',{
mathod:'GET'
}
).then(res=>{
console.log(res.text);
}).then(res=>{
console.log(res);
});
};
fetch方法接受两个参数,第一个必传参数就是接口的url,第二个可选参数是fetch的init项,包括method,
post方法
post传递参数要放在fetch第二个参数的body属性里面
fetch('http://localhost:8080/projectList',{
mathod:'POST',
body: new URLSearchParams([["foo", 1],["bar", 2]]).toString(),
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded'
},
}
).then(res=>{
console.log(res.text);
}).then(res=>{
console.log(res);
});
};
设置请求头:
一般
fetch('http://localhost:8080/projectList?name=123',{
mathod:'GET',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded' //表单提交方式
},
}
).then(res=>{
console.log(res.text);
}).then(res=>{
console.log(res);
});
};
post请求的content-type要设置为表单提交方式
强制带cookie提交
fetch默认是不会像服务器发送或接受cookie的,如果想提交cookie 需要再fetch的第二个参数中添加
credentials:'include'
fetch('http://localhost:8080/projectList?name=123',{
mathod:'GET',
credentials: 'include', //强制带cookie发送到服务器
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded' //表单提交方式
},
}
).then(res=>{
console.log(res.text);
}).then(res=>{
console.log(res);
});
};
补充:
fetch是支持跨域的,只要客户端和浏览器支持