繁体   English   中英

Cors header “访问控制允许来源”被阻止 Api 响应

[英]Cors header “Access-control-allow-origin” blocked Api Response

我有一个 index.html 文件。 该文件用于 html 和 Ajax 调用。 如果我当时通过本地主机运行文件 api 工作完美..

But if i index.html file direct run on Google chrome, Mozilla firefox that time API given cors access control allow origin block error..

    <script type="text/javascript">
        

        $( document ).ready(function() {
            var channel_fid = $(this).attr("data-channel_fid");
            var channel_id = $(this).attr("data-channel_id");
            var userId = $('#uuid').val();
            $.ajax({
                url: 'https://3genrib1y0.execute-api.us-east-1.amazonaws.com/public/users/5ebc3ba8-37e6-4188-b52e-2e18d4a80034/channels',
                type: "GET",
                dataType:'json',
            })
            .done(function(res) {
                if(res.success==true){
                    var val = res.galleries;
                    var options = new Array();
                    $.each(res.galleries, function(index, values) {
                        options.push('<li class="channels-list__item hover'+index+'" data-channel_fid="'+values.gallery_fid+'"><img src="https://www.cincopa.com/media-platform/api/thumb.aspx?size=large&amp;fid='+values.gallery_fid+'"><div class="channels-list__info"><div class="channels-list__itemname"><h3>'+values.name+'</h3></div><div class="channels-list__itemdescr"><p>'+values.description+'</p></div></div></li>');
                    });
                    $('.dropdownItemContainer').html(options);

                }
                else
                {
                    $('.dropdownItemContainer').html('');
                }
            });



            var active = document.querySelector(".hover0") || document.querySelector(".dropdownItemContainer li");

            document.addEventListener("keydown",handler);

            function handler(e){
            // console.log(active.classList);
            active.classList.remove("hover0");
            if (e.which == 40){
                active = active.nextElementSibling || active;
            }else if (e.which == 38){      
                active = active.previousElementSibling || active;
            }else{
                active = e.target;
            }
            active.classList.add("hover0");
        }
    });

</script>

这不是您使用哪种技术堆栈的问题,而是您如何尝试实现 API 消耗的问题。 您正在从可能完全不同的域(例如 example.com)请求远程资源( https://3genrib1y0.execute-api..... )。 现在 chrome 和 firefox 足够聪明,可以保护用户免受试图从外部位置提取数据的站点的攻击 - 除非该站点通过CORS Headers明确声明允许联系它,例如来自 example.Z4D236D9A20D102C5ZFE.AD1

所以 CORS 是在浏览器级别发生的安全功能。 它在本地工作的事实很可能是由于从同一域调用 API,例如调用 127.0.0.1/api 的 127.0.0.1,因此被认为是非跨域资源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM