微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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)  
});

原文地址:https://www.jb51.cc/html5/168895.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。