允许使用HTML5获取API的Access-Control-Allow-Origin标头 [英] Allow Access-Control-Allow-Origin header using HTML5 fetch API

查看:235
本文介绍了允许使用HTML5获取API的Access-Control-Allow-Origin标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HTML5提取API.

I am using 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网址的数据. 它引发错误:

I am able to use normal json but unable to fetch the data of above api url. It throws error:

Fetch API无法加载 https://davidwalsh.name/demo/arsenal.json .所请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许访问来源' http://localhost .如果不透明的响应可以满足您的需求,请将请求的模式设置为"no-cors",以在禁用CORS的情况下获取资源.

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(尽管我相信这是默认设置):

Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):

fetch(request, {mode: 'cors'});

但是,此 still 要求服务器也启用CORS,并允许您的域请求资源.

However this still requires the server to enable CORS as well, and allow your domain to request the resource.

查看 CORS文档,以及此很棒的Udacity视频解释了您还可以在客户端使用no-cors模式,但这只会给您一个不透明的响应(您无法读取主体,但是响应仍可以由服务工作者缓存或由某些API使用,如<img>):

You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>):

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

这篇关于允许使用HTML5获取API的Access-Control-Allow-Origin标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆