[Javascript] Fetch API

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

 

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: Linkpromise

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

 

'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.ide

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

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

 

Morethis

相關文章
相關標籤/搜索