先看一下 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)
});