可能遇到的问题:
- Fetch 请求默认是不带 cookie 的,需要设置 fetch(url, {credentials: 'include'})
- 服务器返回 400,500 错误码时并不会 reject,只有网络错误这些导致请求不能完成时,fetch 才会被 reject。
- 原生fetch没有abort方法,如果用polyfill需要自己封装一个出去,或者安装一个封装完整的包(例如axios)
- fetch的默认请求method是get,若是要特别指定其他类型需要在第二个参数里指定。
使用 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"); });
Fetch + arrow function
fetch(url).then(response => response.json()) .then(data => console.log(data)) .catch(e => console.log("Oops, error", e))
async/await
async function f(url){ try { let response = await fetch(url); let data = await response.json(); console.log(data); } catch(e) { console.log("Oops, error", e); } }
更多例子
fetch('/hello').then((response) => { return response.text(); }).then((data) => { console.log(data); }).catch((e) => { console.log("Oops, error"); }); fetch('/', { method: 'POST' }).then((response) => { return response.text(); }).then((data) => { console.log(data); }).catch((e) => { console.log("Oops, error"); }); fetch('/user', { method: 'PUT' }).then((response) => { return response.text(); }).then((data) => { console.log(data); }).catch((e) => { console.log("Oops, error"); }); fetch('/user', { method: 'DELETE' }).then((response) => { return response.text(); }).then((data) => { console.log(data); }).catch((e) => { console.log("Oops, error"); });
var myImage = document.querySelector('img'); var myHeaders = new Headers(); myHeaders.append('Content-Type', 'image/jpeg'); var myInit = { method: 'GET', headers: myHeaders, mode: 'cors', cache: 'default' }; var myRequest = new Request('flowers.jpg'); fetch(myRequest,myInit).then(function(response) { ... }); //var myRequest = new Request('flowers.jpg',myInit); //fetch(myRequest).then(function(response) { // ... //});