jQuery 访问控制允许来源 - 本地主机

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13893361/
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-08-26 13:04:27  来源:igfitidea点击:

Access-Control-Allow-Origin - localhost

jqueryajaxjsonapihttp-headers

提问by holyredbeard

I have problems with receiving json through ajax, the error is below. According to the information I've found so far regarding the error this seems to be some kind of cross domain issue, but I have no idea of what that means and how to solve it.

我在通过ajax接收json时遇到问题,错误如下。根据到目前为止我发现的有关错误的信息,这似乎是某种跨域问题,但我不知道这意味着什么以及如何解决它。

There may be an issue with the response header (I have created the API myself and have no experiences since before), however a 200 OK is received if accessing the url directly in the browser.

响应头可能有问题(我自己创建了 API,之前没有任何经验),但是如果直接在浏览器中访问 url,则会收到 200 OK。

If accessing the url directly in the browser valid json is shown, so that shouldn't be the problem.

如果显示直接在浏览器中访问 url 有效 json,那么这应该不是问题。

How can this be solved?

如何解决这个问题?

Note: The url goes to an Apache server, not a file that has been the case for 95% of the questions here on Stack that I've read about the issue.

注意:该 url 指向 Apache 服务器,而不是我在 Stack 上阅读过的有关该问题的 95% 问题的文件。

Error in inspector:

检查器中的错误:

XMLHttpRequest cannot load http://localhost/api/v1/products?_=1355583847077.
Origin null is not allowed by Access-Control-Allow-Origin.
Error: error 

The code:

编码:

    $.ajaxSetup ({
      url: "http://localhost/api/v1/products", // <--- returns valid json if accessed in the browser
      type: "GET",
      dataType: "json",
      cache: false,
      contentType: "application/json"
    })
    $.ajax({
        success: function(data){

            console.log("You made it!");
        },
        error: function(xhr) {
           console.log("Error: " + xhr.statusText);
       }
    }).done(function(data){
        console.log(data);
    })

Params

参数

_ 1355583610778

_ 1355583610778

Headers

标题

Response Headers:

响应头:

Connection  Keep-Alive
Content-Length  3887
Content-Type    application/json
Date    Sat, 15 Dec 2012 14:50:53 GMT
Keep-Alive  timeout=5, max=100
Server  Apache/2.2.14 (Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By    PHP/5.3.1

Request Headers:

请求头:

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language sv-SE,sv;q=0.8,en-US;q=0.5,en;q=0.3
Connection  keep-alive
Host    localhost
Origin  null
User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0

Response

回复

Nothing here...

这里没有什么...

采纳答案by Fergus In London

Try and implement some form of JSONPmechanism. If you're using PHP it could be something as simple as this...

尝试并实现某种形式的JSONP机制。如果您使用的是 PHP,它可能就像这样简单......

/* If a callback has been supplied then prepare to parse the callback
 ** function call back to browser along with JSON. */
$jsonp = false;
if ( isset( $_GET[ 'callback' ] ) ) {
    $_GET[ 'callback' ] = strip_tags( $_GET[ 'callback' ] );
    $jsonp              = true;

    $pre  = $_GET[ 'callback' ] . '(';
    $post = ');';
} //isset( $_GET[ 'callback' ] )

/* Encode JSON, and if jsonp is true, then ouput with the callback
 ** function; if not - just output JSON. */
$json = json_encode( /* data here */ );
print( ( $jsonp ) ? $pre . $json . $post : $json );

All this would do is check for a $_GETvar called callback, and then wrap the output in a function call - taking the $_GET['callback']name as a function name.

所有这一切都是检查一个$_GET名为callback的变量,然后将输出包装在一个函数调用中 - 将$_GET['callback']名称作为函数名称。

Then your AJAX call becomes something like this...

然后你的 AJAX 调用变成了这样......

$.ajax({
  type: 'GET',
  url: '/* script here */ ', 
  data: /* data here - if any */,
  contentType: "jsonp", // Pay attention to the dataType/contentType
  dataType: 'jsonp', // Pay attention to the dataType/contentType
  success: function (json) {
    /* call back */
  }
});

When jQuery is given 'jsonp'as a dataType/contentType it will take care of providing a callback function name for you - and setting the callback function up etc; meaning you don't have to do anything really!

当 jQuery'jsonp'作为 dataType/contentType 给出时,它将负责为您提供回调函数名称 - 并设置回调函数等;这意味着您实际上不必做任何事情!

From the jQuery documentation:

来自 jQuery 文档:

"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

“jsonp”:使用 JSONP 加载到 JSON 块中。添加一个额外的“?callback=?” 到 URL 的末尾以指定回调。通过将查询字符串参数“_=[TIMESTAMP]”附加到 URL 来禁用缓存,除非缓存选项设置为 true。

Source

来源

In closing; JSONP is going to be your best bet - I've included PHP code in the off chance that your server side script is using PHP; if not then the principles are the same. The jQuery/client side stuff stays the same regardless of server side technologies though. (in general)

在结束; JSONP 将是你最好的选择——我已经包含了 PHP 代码,以防你的服务器端脚本使用 PHP;如果不是,那么原则是相同的。不管服务器端技术如何,jQuery/客户端的东西都保持不变。(一般情况下

Good luck :)

祝你好运 :)

回答by mekwall

Yep, this is definately a cross-domain issue. But don't fret, there's two solutions to this problem.

是的,这绝对是一个跨域问题。但是不要担心,这个问题有两种解决方案。

Using JSONP

使用 JSONP

You can implement support for JSONP (JSON with padding) on the server (i.e. Fergus Morrow's solution). JSONP works cross-domain out-of-the-box and is basically JSON padded with a function call.

您可以在服务器上实现对 JSONP(带填充的 JSON)的支持(即Fergus Morrow 的解决方案)。JSONP 跨域开箱即用,基本上是用函数调用填充的 JSON。

In your .ajaxSetupset dataTypeto jsonpand then on the server-side you should make sure to check for an url parameter named callbackin the request. If that parameter is set, the JSON response has to be padded accordingly.

在您的.ajaxSetup设置dataTypejsonp,然后在服务器端,您应该确保检查callback请求中命名的 url 参数。如果设置了该参数,则必须相应地填充 JSON 响应。

parseThis({ "json": "can", "be": "put", "in": "here" });

The above assumes callbackis set to parseThis. jQuery will per default generate a function name, but you can override this by setting the value of jsonpCallbackin your .ajaxSetup.

以上假设callback设置为parseThis. jQuery 将默认生成一个函数名称,但您可以通过jsonpCallback.ajaxSetup.

You can also use a shortcut to tell jQuery that you are requesting JSONP by just adding ?callback=?to the request url.

您还可以使用快捷方式告诉 jQuery 您正在请求 JSONP,只需添加?callback=?到请求 url 即可。

Using Access-Control-Allow-Origin

使用 Access-Control-Allow-Origin

An alternate solution is to set the Access-Control-Allow-Originheader in your response.

另一种解决方案是Access-Control-Allow-Origin在响应中设置标头。

Access-Control-Allow-Origin: *

The above will allow anyresource to use the service cross-domain. Read up on the article linked below for more information on how to configure Access-Control-Allow.

以上将允许任何资源跨域使用服务。阅读下面链接的文章,了解有关如何配置Access-Control-Allow.



If you want to know more on Access-Control-Origin and CORS I recommend this article on MDN.

如果你想了解更多关于 Access-Control-Origin 和 CORS 的信息,我推荐MDN 上的这篇文章

回答by holyredbeard

I solved it in a very easy way, by adding the following header to my server code (php):

我以一种非常简单的方式解决了这个问题,方法是在我的服务器代码 (php) 中添加以下标头:

header('Access-Control-Allow-Origin: *');

回答by Vasile Laur

If it's an ASP.NET WEB application then you can also put this in your Global.aspx:

如果它是一个 ASP.NET WEB 应用程序,那么你也可以把它放在你的 Global.aspx 中:

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

回答by Thabelo Phusu Mmbengeni

More PHP header settings

更多 PHP 标头设置

header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');

Good Luck

祝你好运