简体   繁体   English

Access-Control-Allow-Origin - localhost

[英]Access-Control-Allow-Origin - localhost

I have problems with receiving json through ajax, the error is below. 我通过ajax接收json有问题,错误如下。 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. 根据我迄今为止发现的关于错误的信息,这似乎是某种跨域问题,但我不知道这意味着什么以及如何解决它。

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 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... 这里没有什么...

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 (ie Fergus Morrow's solution ). 您可以在服务器上实现对JSONP(带填充的JSON)的支持(即Fergus Morrow的解决方案 )。 JSONP works cross-domain out-of-the-box and is basically JSON padded with a function call. JSONP开箱即用的跨域工作,基本上是JSON填充函数调用。

In your .ajaxSetup set dataType to jsonp and then on the server-side you should make sure to check for an url parameter named callback in the request. .ajaxSetup中将dataType设置为jsonp ,然后在服务器端,您应该确保在请求中检查名为callback的url参数。 If that parameter is set, the JSON response has to be padded accordingly. 如果设置了该参数,则必须相应地填充JSON响应。

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

The above assumes callback is set to parseThis . 以上假设callback设置为parseThis jQuery will per default generate a function name, but you can override this by setting the value of jsonpCallback in your .ajaxSetup . jQuery将每默认生成的函数名,但你可以通过设置的值覆盖此jsonpCallback.ajaxSetup

You can also use a shortcut to tell jQuery that you are requesting JSONP by just adding ?callback=? 您还可以使用快捷方式通过添加?callback=?告诉jQuery您正在请求JSONP ?callback=? to the request url. 到请求网址。

Using Access-Control-Allow-Origin 使用Access-Control-Allow-Origin

An alternate solution is to set the Access-Control-Allow-Origin header in your response. 另一种解决方案是在响应中设置Access-Control-Allow-Origin标头。

Access-Control-Allow-Origin: *

The above will allow any resource 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上使用本文

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

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

Try and implement some form of JSONP mechanism. 尝试并实现某种形式的JSONP机制。 If you're using PHP it could be something as simple as this... 如果您正在使用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 $_GET var called callback , and then wrap the output in a function call - taking the $_GET['callback'] name as a function name. 所有这一切都是检查$_GET var调用回调 ,然后将输出包装在函数调用中 - 将$_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; 当jQuery被赋予'jsonp'作为dataType / contentType时,它将负责为你提供一个回调函数名称 - 并设置回调函数等; meaning you don't have to do anything really! 意思是你真的不需要做任何事情!

From the jQuery documentation: 从jQuery文档:

"jsonp": Loads in a JSON block using JSONP. “jsonp”:使用JSONP加载JSON块。 Adds an extra "?callback=?" 添加额外的“?callback =?” to the end of your URL to specify the callback. 到URL的末尾以指定回调。 Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. 通过将查询字符串参数“_ = [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; JSONP将是你最好的选择 - 我已经包含了PHP代码,因为你的服务器端脚本正在使用PHP; if not then the principles are the same. 如果没有那么原则是相同的。 The jQuery/client side stuff stays the same regardless of server side technologies though. 不管服务器端技术如何,jQuery /客户端的东西都保持不变。 ( in general ) 一般情况下

Good luck :) 祝好运 :)

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”,“*”);

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 祝好运

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

相关问题 本地主机上没有“ Access-Control-Allow-Origin” - No 'Access-Control-Allow-Origin' on the localhost Access-Control-Allow-Origin不允许来源http:// localhost:8080 - Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin 原始本地主机:Access-Control-Allow-Origin不允许 - Origin localhost: is not allowed by Access-Control-Allow-Origin Access-Control-Allow-Origin不允许使用origin http:// localhost:1716 - Origin http://localhost:1716 is not allowed by Access-Control-Allow-Origin Ajax-&#39;Origin localhost不允许Access-Control-Allow-Origin&#39; - Ajax - 'Origin localhost is not allowed by Access-Control-Allow-Origin' XMLHttpRequest无法加载...在localhost中没有&#39;Access-Control-Allow-Origin&#39;... - XMLHttpRequest cannot load … No 'Access-Control-Allow-Origin'…in localhost? 访问控制允许来源 - Access-Control-Allow-Origin Access-Control-Allow-Origin 不允许来源 - Origin is not allowed by Access-Control-Allow-Origin XMLHttpRequest无法加载http:// localhost:8089 / jquery。 Access-Control-Allow-Origin不允许使用原点null - XMLHttpRequest cannot load http://localhost:8089/jquery. Origin null is not allowed by Access-Control-Allow-Origin XMLHTTPRequest无法加载http:// ...原始http:// localhost:Access-Control-Allow-Origin不允许使用端口 - XMLHTTPRequest cannot load http://… Origin http://localhost:port is not allowed by Access-Control-Allow-Origin
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM