版权声明:经验之谈,不足之处望指正。珍惜劳动成果 https://blog.csdn.net/ange2017/article/details/88837458
先看一下 Fetch 原生支持率:
Fetch 常见坑
-
Fetch 请求默认是不带 cookie 的,需要设置
fetch(url, {credentials: 'include'})
-
服务器返回 400,500 错误码时并不会 reject,只有网络错误这些导致请求不能完成时,fetch 才会被 reject。
基本用法:
fetch(url, option).then(function (response) {
// handle HTTP response
console.log('请求成功')
}, function (error) {
// handle network error
console.log('请求失败')
})
常用写法:
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');
var option = {
method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default'
};
var myRequest = new Request(url, option);
fetch(myRequest).then(function (response) {
console.log(response)
});