Access-Control-Allow-Origin 不允许来源

我正在向 中的远程 PHP 服务器发出 Ajax.requestSencha Touch 2 应用程序(包装在 PhoneGap 中).

I'm making an Ajax.request to a remote PHP server in a Sencha Touch 2 application (wrapped in PhoneGap).

服务器的响应如下:

XMLHttpRequest 无法加载 http://nqatalog.negroesquisso.pt/login.php.Access-Control-Allow-Origin 不允许来源 http://localhost:8888.

XMLHttpRequest cannot load http://nqatalog.negroesquisso.pt/login.php. Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.

我该如何解决这个问题?

How can I fix this problem?

推荐答案

前段时间我写了一篇关于这个问题的文章,跨域 AJAX.

I wrote an article on this issue a while back, Cross Domain AJAX.

如果您可以控制响应服务器,则处理此问题的最简单方法是为以下内容添加响应标头:

The easiest way to handle this if you have control of the responding server is to add a response header for:

Access-Control-Allow-Origin: *

这将允许跨域 Ajax.在 PHP 中,您需要像这样修改响应:

This will allow cross-domain Ajax. In PHP, you'll want to modify the response like so:

<?php header('Access-Control-Allow-Origin: *'); ?>

您只需将 Header set Access-Control-Allow-Origin * 设置放在 Apache 配置或 htaccess 文件.

You can just put the Header set Access-Control-Allow-Origin * setting in the Apache configuration or htaccess file.

应该注意的是,这会有效地禁用 CORS 保护,这很可能会使您的用户受到攻击.如果您不知道自己特别需要使用通配符,则不应使用它,而应将您的特定域列入白名单:

It should be noted that this effectively disables CORS protection, which very likely exposes your users to attack. If you don't know that you specifically need to use a wildcard, you should not use it, and instead you should whitelist your specific domain:

<?php header('Access-Control-Allow-Origin: http://example.com') ?>

相关文章