HTML5 fetch API
本文由 小茗同学 发表于 2017-03-08 浏览(7369)
最后修改 2019-06-11 标签:html5 fetch javascript

介绍

fetch是传统XMLHttpRequest(也就是常说的ajax)的替代者,相比后者,它更简单,并且内置对Promise的支持。

但其实话说回来,我至今没太搞明白它的更多优点,因为说它使用简单好像体现不出优势,因为我们平时都是使用ajax框架的(比如jQuery),很少会直接使用原生XMLHttpRequest,而且用了它的话还要担心兼容性的问题。

语法

语法很简单:fetch(url, config),返回一个Promise对象。

基本使用

请求某个网页:

fetch('http://localhost/index.html')
	.then(response => response.text())
	.then(data => console.log(data));

请求某个JSON接口:

fetch('http://localhost/test.json')
	.then(response => response.json())
	.then(data => console.log(data));

请求某个图片:

fetch('http://localhost/test.jpg').then(response => response.blob())
.then(data =>
{
	var img = new Image();
	img.src = URL.createObjectURL(data); // 这个data是blob对象
	document.body.appendChild(img);
});

Post请求

fetch('https://blog.haoji.me/xxx.json', {
	method: 'POST',
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
	},
	body: 'a=1&b=2',
}).then(resp => resp.json()).then(resp => {
	console.log(resp)
});

fetch默认是不携带cookie的,需要手动添加一个配置参数credentials: 'include'

fetch('http://localhost/test.json', {credentials: 'include'})
	.then(response => response.json())
	.then(data => console.log(data));

更多用法

自定义header

var headers = new Headers(
{
	"Content-Type": "text/plain",
	"X-Custom-Header": "aaabbbccc",
});
var formData = new FormData();
formData.append('name', 'lxa');
formData.append('file', someFile);
var config =
{
	credentials: 'include', // 支持cookie
	headers: headers, // 自定义头部
	method: 'POST', // post方式请求
	body: formData // post请求携带的内容
};
fetch('http://localhost/test.json', config)
	.then(response => response.json())
	.then(data => console.log(data));

当然,headers也可以这么初始化:

var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");

兼容性

兼容性目前不太好,Chrome42+和Firefox39+支持,IE全系列不支持。

参考

更多高级用法,还是去MDN上查看完整介绍:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch