有一个用于从JavaScript发出请求的新API:fetch().是否有任何内置机制可以在飞行中取消这些请求?
我可以http://catfacts-api.appspot.com/api/facts?number=99通过Postman 点击这个终点并返回JSON
此外,我正在使用create-react-app,并希望避免设置任何服务器配置.
在我的客户端代码中我试图用fetch同样的东西,但我收到错误:
请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:3000 '访问.如果不透明响应满足您的需求,请将请求的模式设置为"no-cors"以获取禁用CORS的资源.
所以我试图传入一个对象,我的Fetch将禁用CORS,如下所示:
fetch('http://catfacts-api.appspot.com/api/facts?number=99', { mode: 'no-cors'})
.then(blob => blob.json())
.then(data => {
console.table(data);
return data;
})
.catch(e => {
console.log(e);
return e;
});
Run Code Online (Sandbox Code Playgroud)
有趣的是,我得到的错误实际上是这个函数的语法错误.我不确定我的实际fetch是否已损坏,因为当我删除{mode:'no-cors'}对象,并为其提供不同的URL时,它可以正常工作.
我也尝试传入该对象{ mode: 'opaque'},但这会从上面返回原始错误.
我相信我需要做的就是禁用CORS ..我错过了什么?
典型的AJAX和Fetch API有什么区别?
考虑这种情况:
function ajaxCall(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
ajaxCall('www.testSite').then(x => {
console.log(x)
}) // returns html of site
fetch('www.testSite').then(x => {
console.log(x)
}) // returns object with information about call
Run Code Online (Sandbox Code Playgroud)
这是fetch调用返回的内容:
Response {type: "cors", url: "www.testSite", status: 200, ok: true, statusText: "OK"…} …Run Code Online (Sandbox Code Playgroud) 我最近一直在使用fetch API和Promises,我遇到了.json().通常.json()返回与JSON.parse相同的输出.我用Google搜索了问题,结果指向了其他方向.
XHR和JSON.parse示例:
$('#xhr').click(function(){
var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function(){
if (XHR.status == 200 && XHR.readyState == 4) {
$('#quote').text(JSON.parse(XHR.responseText)[0]);
}
};
XHR.open("GET", url);
XHR.send();
});
Run Code Online (Sandbox Code Playgroud)
使用Fetch API的示例:
$('#fetch').click(function(){
fetch(url)
.then(function(res){
return res.json();
})
.then(function(quote){
$('#quote').text(quote);
})
.catch(function(err){
handleError(err);
});
});
Run Code Online (Sandbox Code Playgroud)
有人可以解释这些看似相似的概念之间的区别吗?谢谢