使用HTML5 fetch API允许Access-Control-Allow-Origin标头

我正在使用HTML5 fetch API。
var request = new Request('https://davidwalsh.name/demo/arsenal.json');

        fetch(request).then(function(response) {
        // Convert to JSON
            return response.json();
        }).then(function(j) {
            // Yay,`j` is a JavaScript object
            console.log(JSON.stringify(j)); 
        }).catch(function(error) {  
            console.log('Request Failed',error)  
        });

我能够使用普通的json但无法获取上述api url的数据。
它抛出错误

Fetch API cannot load https://davidwalsh.name/demo/arsenal.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. If an opaque response serves your needs,set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

解决方法

像epascarello所说,托管资源的服务器需要启用CORS。您可以在客户端(也可能是您正在考虑的)设置获取CORS的模式(尽管这是我认为的认设置):
fetch(request,{mode: 'cors'});

但是,这仍然需要服务器启用CORS,并允许您的域请求资源。

查看CORS documentation,以及awesome Udacity video解释Same Origin Policy

您也可以在客户端使用no-cors模式,但这只会给您一个不透明的响应(您无法读取正文,但响应仍然可以由服务工作者缓存或由某些API使用,例如< ; IMG&GT):

fetch(request,{mode: 'no-cors'})
.then(function(response) {
  console.log(response); 
}).catch(function(error) {  
  console.log('Request Failed',error)  
});

相关文章

HTML5和CSS3实现3D展示商品信息的代码
利用HTML5中的Canvas绘制笑脸的代码
Html5剪切板功能的实现
如何通过HTML5触摸事件实现移动端简易进度条
Html5移动端获奖无缝滚动动画实现
关于HTML5和CSS3实现机器猫的代码