码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Fetch API

时间:2016-06-25 21:46:28      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

fetch() does the same thing as XHR, but fetch return a promise.

 

fetch(password.txt, {
  method: PUT,
  headers: {
    X-Something-nothing: fetch rocks!
  }
}).then( response => {
  if(response.status === 200){
    return response.text()
  }else{
    throw "Cannot fetch data"
  }
}).then( data => {
  console.log(data);
}).catch( err => {
  console.error(err)
})

 

Check the reponse API here: Link

Besides text(), you can use json() or blob().

 

‘no-cors‘ and opaque responses

If I request //google.com from this site using XHR or plain fetch it will fail. This is because it‘s a CORS request and the response doesn‘t have CORS headers.

However, with fetch, you can make a no-cors request:

fetch(//google.com, {
  mode: no-cors
}).then(function(response) {
  console.log(response.type); // "opaque"
});

 

More

[Javascript] Fetch API

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5616890.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!