使用 HTML5 fetch API 允许 Access

编程入门 行业动态 更新时间:2024-10-24 06:30:28
本文介绍了使用 HTML5 fetch API 允许 Access-Control-Allow-Origin 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 16:52:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/943650.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:fetch   Access   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!