标签:
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().
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" });
标签:
原文地址:http://www.cnblogs.com/Answer1215/p/5616890.html