我在做一个Ajax。请求一个远程PHP服务器在Sencha Touch 2应用程序(包装在PhoneGap)。

服务器的响应如下:

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

我该如何解决这个问题?


当前回答

当您收到请求时,您可以

var origin = (req.headers.origin || "*");

而当你不得不这样回答的时候:

res.writeHead(
    206,
    {
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': origin,
    }
);

其他回答

这是我在尝试使用ASP解决相同问题时出现的第一个问题/答案。NET MVC作为数据源。我知道这并不能解决PHP的问题,但是它与PHP的关系是有价值的。

我使用ASP。净MVC。Greg Brant的博客文章对我很有用。最终,您将创建一个属性[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")],您可以将其添加到控制器操作中。

例如:

public class HttpHeaderAttribute : ActionFilterAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }
    public HttpHeaderAttribute(string name, string value)
    {
        Name = name;
        Value = value;
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.AppendHeader(Name, Value);
        base.OnResultExecuted(filterContext);
    }
}

然后用它:

[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
public ActionResult MyVeryAvailableAction(string id)
{
    return Json( "Some public result" );
}

如果你正在使用Apache,只需添加:

<ifModule mod_headers.c>
    Header set Access-Control-Allow-Origin: *
</ifModule>

在构型中。这将导致来自您的web服务器的所有响应都可以从互联网上的任何其他站点访问。如果你打算只允许你的主机上的服务被特定的服务器使用,你可以用原始服务器的URL替换*:

Header set Access-Control-Allow-Origin: http://my.origin.host

当您收到请求时,您可以

var origin = (req.headers.origin || "*");

而当你不得不这样回答的时候:

res.writeHead(
    206,
    {
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': origin,
    }
);

如果你不能控制服务器,你可以简单地在Chrome启动器中添加这个参数:——disable-web-security。

注意,我不会将它用于正常的“网上冲浪”。参考:在Chrome中禁用同源策略。

如果你使用Phonegap来构建应用并将其加载到设备上,这就不是问题了。

我们也有同样的问题,phonegap应用程序在chrome测试。 在打开Chrome之前,我们每天使用下面的批处理文件。 记住在运行这个之前,你需要从任务管理器中清除所有的chrome实例,或者你可以选择chrome不运行在后台。

BATCH:(使用cmd)

cd D:\Program Files (x86)\Google\Chrome\Application\chrome.exe --disable-web-security