簡單來說Fetch API就是一個請求資源的接口,比XMLHttpRequest更簡單。
Fetch支持跨源資源共享(CORS),正式環境需要HTTPS。
請求示例:
fetch('examples/example.json')
.then(function(response) {
if (!response.ok) {
throw Error(response.statusText);
}
// Read the response as json.
return response.json();//這里可以響應json、text、blob等
})
.then(function(responseAsJson) {
// Do stuff with the JSON
console.log(responseAsJson);
})
.catch(function(error) {
console.log('Looks like there was a problem: \n', error);
});
自定義請求
1、設置請求方法
fetch('examples/words.txt', {
method: 'HEAD'
})
2、POST請求
//基本方式
fetch('someurl/comment', {
method: 'POST',
body: 'title=hello&message=world'
})
// form表單方式
fetch('someurl/comment', {
method: 'POST',
body: new FormData(document.getElementById('myForm')
})
3、定義header
var myHeaders = new Headers({
'Content-Type': 'text/plain',
'X-Custom-Header': 'hello world'
});
fetch('/someurl', {
headers: myHeaders
});
4、跨域請求
通常跨越解決方案:
jsonp、服務端設置Access-Control-Allow-Origin:*、添加mode:'no-cors'
// 添加mode
fetch('http://bar.com/data.json', {
mode: 'no-cors' // 'cors' by default
})
.then(function(response) {
// Do something with response
});
參考鏈接:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API