[Javascript] Fetch API

时间:2021-03-16 20:17:49

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 === ){
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