简体   繁体   English

为什么我收到跨域请求被阻止的原因:同源策略禁止读取远程资源

[英]Why do I get a Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

Okay so I am playing around with using API's and currently I am using the geonames api. 好的,所以我正在使用API​​进行操作,目前正在使用地理名称api。 My problem is it works fine until... 我的问题是直到...

Let me explain, when I write the code as such 让我解释一下,当我编写这样的代码时

$(document).ready(function() {


        Date.prototype.dateToString = function() {
               var yyyy = this.getFullYear().toString();
               var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
               var dd  = this.getDate().toString();
               return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]); // padding
        };

        var d = new Date();
        var date = d.dateToString();


        $.ajax({
            dataType: "json",
            url: url
        }).then(function(data){

            var latitude = data.geonames[0].lat;
            var longitude = data.geonames[0].lng;

            var north = parseFloat(latitude) + 1;
            var south = parseFloat(latitude) - 1;
            var east = parseFloat(longitude) + 1;
            var west = parseFloat(longitude) - 1;

            var uri = encodeURI("http://api.geonames.org/earthquakesJSON?north=" + north + "&south=" + south + "&east=" + east + "&west=" + west + "&date=" + date +"&username=demo"); 

            $.ajax({
                dataType: "json",
                url: uri
            }).then(function(eData){

                var myLatlng = new google.maps.LatLng(parseFloat(data.geonames[0].lat), parseFloat(data.geonames[0].lng));

                function initialize() {

                    var mapProp = {
                        center : myLatlng,
                        minzoom: 1,
                        maxzoom: 20,
                        zoom : 7,
                        mapTypeId : google.maps.MapTypeId.ROADMAP
                    };

                    var map = new google.maps.Map(document.getElementById("googleMap"),
                        mapProp);

                    var marker = new google.maps.Marker({
                        position: myLatlng,
                        map: map,
                        title: 'Search Location\nLatitude: ' + data.geonames[0].lat + '\nLongitude: ' + data.geonames[0].lng  
                    }); 

                    for(item = 0; item < eData.earthquakes.length; item++){

                        if (eData.earthquakes.length > 0){
                            var eLat = eData.earthquakes[item].lat, eLng = eData.earthquakes[item].lng;
                        } else {
                            var eLat = '', eLng = '';
                        }
                        new google.maps.Marker({
                            position: new google.maps.LatLng(eLat,eLng),
                            map: map,
                            title: 'Date and Time: '+eData.earthquakes[item].datetime+'\nMagnitude: '+eData.earthquakes[item].magnitude+'\nDepth: '+eData.earthquakes[item].depth+'\nLat: '+eData.earthquakes[item].lat+'\nLong: '+eData.earthquakes[item].lng 
                        });
                    }
                }
                initialize();

                });
            });
        });

It will work just fine, loads when the page comes up as it is supposed to do, However if I wrap it in a function like this 它可以正常工作,按预期的方式在页面出现时加载,但是如果我将其包装在这样的函数中

 function getSearch(url){
    $(document).ready(function() {


        Date.prototype.dateToString = function() {
               var yyyy = this.getFullYear().toString();
               var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
               var dd  = this.getDate().toString();
               return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]); // padding
        };

        var d = new Date();
        var date = d.dateToString();


        $.ajax({
            dataType: "json",
            url: url
        }).then(function(data){

            var latitude = data.geonames[0].lat;
            var longitude = data.geonames[0].lng;

            var north = parseFloat(latitude) + 1;
            var south = parseFloat(latitude) - 1;
            var east = parseFloat(longitude) + 1;
            var west = parseFloat(longitude) - 1;

            var uri = encodeURI("http://api.geonames.org/earthquakesJSON?north=" + north + "&south=" + south + "&east=" + east + "&west=" + west + "&date=" + date +"&username=demo"); 

            $.ajax({
                dataType: "json",
                url: uri
            }).then(function(eData){

                var myLatlng = new google.maps.LatLng(parseFloat(data.geonames[0].lat), parseFloat(data.geonames[0].lng));

                function initialize() {

                    var mapProp = {
                        center : myLatlng,
                        minzoom: 1,
                        maxzoom: 20,
                        zoom : 7,
                        mapTypeId : google.maps.MapTypeId.ROADMAP
                    };

                    var map = new google.maps.Map(document.getElementById("googleMap"),
                        mapProp);

                    var marker = new google.maps.Marker({
                        position: myLatlng,
                        map: map,
                        title: 'Search Location\nLatitude: ' + data.geonames[0].lat + '\nLongitude: ' + data.geonames[0].lng  
                    }); 

                    for(item = 0; item < eData.earthquakes.length; item++){

                        if (eData.earthquakes.length > 0){
                            var eLat = eData.earthquakes[item].lat, eLng = eData.earthquakes[item].lng;
                        } else {
                            var eLat = '', eLng = '';
                        }
                        new google.maps.Marker({
                            position: new google.maps.LatLng(eLat,eLng),
                            map: map,
                            title: 'Date and Time: '+eData.earthquakes[item].datetime+'\nMagnitude: '+eData.earthquakes[item].magnitude+'\nDepth: '+eData.earthquakes[item].depth+'\nLat: '+eData.earthquakes[item].lat+'\nLong: '+eData.earthquakes[item].lng 
                        });
                    }
                }
                initialize();

                });
            });
        });
}

I get this error.... 我收到此错误...。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote 
resource at http://api.geonames.org/searchJSON?q=Fukushima&maxRows=10&username=demo. 
This can be fixed by moving the resource to the same domain or enabling CORS.

I haven't done enough server side or working with API's to know exactly what this means, or why the only time it happens is if I am trying to call this method from a form. 我还没有做足够的服务器端工作,也没有使用API​​来确切地知道这意味着什么,或者为什么唯一的一次发生是如果我试图从表单中调用此方法呢?

EDIT::: 编辑:::

While typing this I realized that it wasn't the wrapping in the function that was doing it but rather the changing of the URL when the form was submitted hence the mention of the domain in the error, I should have slowed down to read a little better. 在输入此内容时,我意识到执行此操作的不是函数包装,而是提交表单时更改URL,因此在错误中提及域,我应该放慢速度来阅读一些内容更好。 However since I am doing this in javascript and ajax I would like to know since I do know that form handling can be done without invoking the server how would I go about doing that. 但是,由于我正在用javascript和ajax进行此操作,因此我想知道,因为我确实知道可以在不调用服务器的情况下完成表单处理。

I understand if no one gives a direct answer I actually prefer that no one does but rather points me in the direction of documentation for client side form handling with javascript and ajax with a brief explanation or history of its use. 我知道,如果没有人给出直接答案,我实际上更愿意没人这样做,而是将我指向使用javascript和ajax进行客户端表单处理的文档说明,并简要说明其使用历史。

Thank you all! 谢谢你们!

CORS (cross-origin resource sharing) stipulates that AJAX requests fired from a browser can only contact their same host. CORS(跨域资源共享)规定,从浏览器触发的AJAX请求只能联系其同一主机。 This means that JavaScript running on disney.com can only make AJAX requests to other disney.com endpoints. 这意味着在disney.com上运行的JavaScript只能向其他disney.com端点发出AJAX请求。

Your issue is that you're sending a request to api.geonames.org even though you are likely running on your own host, not an api.geonames.org site. 您的问题是,即使您可能在自己的主机(而不是api.geonames.org站点)上运行,您仍在向api.geonames.org发送请求。

Servers can enable CORS, meaning that they will accept requests from other domains. 服务器可以启用CORS,这意味着它们将接受来自其他域的请求。 However, each server is different and most APIs still do not allow cross-origin requests. 但是,每个服务器都不同,大多数API仍不允许跨域请求。 It looks like api.geonames.org is one of these that does not support CORS. api.geonames.org似乎是其中之一,不支持CORS。

Note that CORS only applies to requests sent from a browser. 请注意,CORS仅适用于从浏览器发送的请求。 Hitting that API from a backend server (like Node or Rails) will work just fine. 从后端服务器(例如Node或Rails)中获取该API即可正常工作。

暂无
暂无

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

相关问题 跨域请求被阻止:“相同来源策略”不允许读取远程资源 - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource a 跨源请求被阻止:同源策略不允许读取远程资源 - react js - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource - react js Cross-Origin Request Blocked:同源策略不允许读取远程资源。 CORS 预检响应未成功 - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. CORS preflight response did not succeed Cross-Origin Request Blocked:同源策略不允许读取远程资源。 (原因:CORS 预检响应没有成功) - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. (Reason: CORS preflight response did not succeed) 跨域请求被阻止:同源策略不允许读取位于 https://localhost:8000/users/login 的远程资源 - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8000/users/login 同一起源策略不允许读取远程资源 - The Same Origin Policy disallows reading the remote resource 浏览器中的“跨源请求被阻止:同源策略”错误 - “Cross-Origin Request Blocked: The Same Origin Policy” Error in browser OPTIONS net::ERR_CONNECTION_REFUSED + 同源策略不允许读取远程资源(原因:CORS 请求没有成功) - OPTIONS net::ERR_CONNECTION_REFUSED + The Same Origin Policy disallows reading the remote resource (Reason: CORS request did not succeed) Angular / Laravel CORS问题:同源策略不允许读取远程资源 - Angular/Laravel CORS issue : The Same Origin Policy disallows reading the remote resource Angular JS-跨域请求在GET请求中被阻止 - Angular js - Cross-Origin Request Blocked in GET request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM