javascript Access-Control-Allow-Origin 不允许 XMLHttpRequest Origin

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8176913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:33:10  来源:igfitidea点击:

XMLHttpRequest Origin is not allowed by Access-Control-Allow-Origin

javascriptxmlhttprequest

提问by Naftuli Kay

I'm trying to fetch some simple text over HTTP from JavaScript:

我正在尝试从 JavaScript 通过 HTTP 获取一些简单的文本:

$(function() {
    $.get("http://mydomain.com/path", function(result) {
        console.log(result);
    });
});

The result should be text/html, but is basically only a simple key-value string, no HTML tags whatsoever. The page is in my control, but is supplied by a third-party (closed-source) so I can't modify the Java that serves out this page.

结果应该是text/html,但基本上只是一个简单的键值字符串,没有任何 HTML 标签。该页面在我的控制之下,但由第三方(封闭源代码)提供,因此我无法修改提供此页面的 Java。

How can I get the contents of this page from JavaScript?

如何从 JavaScript 获取此页面的内容?

回答by Craig White

You've simply gotta use either PHP/ASPyour serverside languageto retrieve the cross-domain request or use a service such as a cross domain ajax service created by Yahoo!.

您只需使用您的服务器端语言PHP/ASP来检索跨域请求或使用诸如由 Yahoo! 创建的跨域 ajax 服务之类的服务。

It uses JSONP which is allowed to do very strict cross-domain requests, but asking from Yahoo! they will retrieve any page on the internet.

它使用 JSONP,允许执行非常严格的跨域请求,但需要从 Yahoo! 他们将检索互联网上的任何页面。

http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

回答by alex

You can't request that page because of Same Origin Policyunless that page has explicitly allowed you with CORS.

由于同源策略,您无法请求该页面,除非该页面明确允许您使用CORS

Either proxy it server side, with a service such as YQL, get it as JSONP or get the other service to enable CORS for your domain.

使用 YQL 等服务代理它的服务器端,将其作为 JSONP 获取,或者获取其他服务来为您的域启用 CORS。