访问控制允许来源 - 本地主机 [英] Access-Control-Allow-Origin - localhost

查看:25
本文介绍了访问控制允许来源 - 本地主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

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

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

如何解决?

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

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

代码:

    $.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);
    })

参数

_1355583610778

Params

_ 1355583610778

响应头:

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

请求标头:

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...

推荐答案

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

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

/* 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 );

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

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.

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

Then your AJAX call becomes something like this...

$.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 */
  }
});

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

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":使用 JSONP 加载到 JSON 块中.添加一个额外的?callback=?"到 URL 的末尾以指定回调.通过将查询字符串参数_=[TIMESTAMP]"附加到 URL 来禁用缓存,除非缓存选项设置为 true.

"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 将是你最好的选择——我已经包含了 PHP 代码,以防你的服务器端脚本使用 PHP;如果不是,那么原则是相同的.不管服务器端技术如何,jQuery/客户端的东西都保持不变.(一般)

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)

祝你好运:)

这篇关于访问控制允许来源 - 本地主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆