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

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

问题描述

我正在使用 HTML5 fetch 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 url 的数据.它抛出错误:

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'});

然而,这仍然要求服务器也启用 CORS,并允许您的域请求资源.

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

查看 CORS 文档,以及这个 很棒的 Udacity 视频 解释了 同源政策.

Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.

你也可以在客户端使用 no-cors 模式,但这只会给你一个不透明的响应(你不能读取正文,但响应仍然可以被服务工作者缓存或被某些 API 使用,比如 ):

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 fetch API 允许 Access-Control-Allow-Origin 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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