'Access-Control-Allow-Origin'Google金融转换器报错javascript/jquery

'Access-Control-Allow-Origin' Google finance converter gives an error javascript/jquery

我正在使用一个项目模块,我想在其中根据货币代码和金额从 Google 财务转换器获取转换后的价格。 这是我的代码:

$('.actual-price').tooltip({
    content: function(callback) {
        var url = 'https://www.google.com/finance/converter?a=25&from=USD&to=AMD';
        $.get(url, {}, function(data) {            
            callback(data);
        });
    },
    open: function(event, ui) {
        var $id = $(ui.tooltip).attr('id');
        $('div.ui-tooltip').not('#' + $id).remove();
    },
    close: function(event, ui) {
        $('.ui - tooltip').hide();
    }
});

它给我一个错误:

XMLHttpRequest cannot load https://www.google.com/finance/converter?a=25&from=USD&to=AED. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://mytestsite.com is therefore not allowed access.

我尝试了以下方法来解决它,但似乎对我没有任何作用!

首先: 添加 Access-Control-Allow-Origin 到网络配置。

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

第二:使用数据类型jsonp:

dataType: "jsonp",

并且已经引用了以下帖子:

“No 'Access-Control-Allow-Origin' header is present on the requested resource”

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access

“No 'Access-Control-Allow-Origin' header is present on the requested resource”

方面:它在我的本地主机上工作,但是当我尝试使用另一个域时,它给我一个错误!

必须允许访问来源也在旁边,当您发送请求时。如果没有,你可以安装一些 browser extensions to bypass it or download entire page (php) end then process it, but you can also try cors-anywhere.herokuapp.com:

var myUrl = 'http://www.geoplugin.net/json.gp?ip=216.58.209.68';

var proxy = 'https://cors-anywhere.herokuapp.com/';

var finalURL = proxy + myUrl;

// With the get JSON (frequently used) method
$.getJSON(finalURL, function( data ) {
    console.log(data);
});

// With the get method
$.get(finalURL, function( data ) {
    console.log(data);
});

// With the post method
$.post(finalURL, function( data ) {
    console.log(data);
});   

More here

为什么您的应用程序可以在 localhost 主机上运行?我认为这是因为 Google 已将访问源设置为允许从其域和本地主机进行连接。

您需要更改 Ajax 设置 async: false 如下:

JavaScript代码:

$('.actual-price').tooltip({
    content: function(callback) {
        var url = 'https://www.google.com/finance/converter?a=25&from=USD&to=AMD';
        $.ajaxSetup({async: false}); ////////// Added
        $.get(url, {}, function(data) {            
            callback(data);
        });
    },
    open: function(event, ui) {
        var $id = $(ui.tooltip).attr('id');
        $('div.ui-tooltip').not('#' + $id).remove();
    },
    close: function(event, ui) {
        $('.ui - tooltip').hide();
    }
});

如果您在本地使用 chrome just add this to your browser

,当您尝试在没有 Web 服务器的情况下从本地向另一台服务器发出请求时,这是一个错误

当您将应用程序上传到生产服务器时将正常工作。因为这只是浏览器阻止此类请求的本地问题。