我在做一个Ajax。请求一个远程PHP服务器在Sencha Touch 2应用程序(包装在PhoneGap)。
服务器的响应如下:
XMLHttpRequest无法加载http://nqatalog.negroesquisso.pt/login.php。Access-Control-Allow-Origin不允许Origin http://localhost:8888。
我该如何解决这个问题?
我在做一个Ajax。请求一个远程PHP服务器在Sencha Touch 2应用程序(包装在PhoneGap)。
服务器的响应如下:
XMLHttpRequest无法加载http://nqatalog.negroesquisso.pt/login.php。Access-Control-Allow-Origin不允许Origin http://localhost:8888。
我该如何解决这个问题?
当前回答
如果你有ASP。Net / asp。NET MVC应用程序,您可以通过Web包含此头文件。配置文件:
<system.webServer>
...
<httpProtocol>
<customHeaders>
<!-- Enable Cross Domain AJAX calls -->
<remove name="Access-Control-Allow-Origin" />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
其他回答
如果你有ASP。Net / asp。NET MVC应用程序,您可以通过Web包含此头文件。配置文件:
<system.webServer>
...
<httpProtocol>
<customHeaders>
<!-- Enable Cross Domain AJAX calls -->
<remove name="Access-Control-Allow-Origin" />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
正如Matt Mombrea在服务器端所说的那样,你可能会遇到另一个问题,即白名单拒绝。
你必须配置你的phonegap。plist。(我正在使用旧版本的phonegap)
对于cordova,命名和目录可能会有一些更改。但步骤应该大致相同。
首先选择支持文件> PhoneGap.plist
然后在“ExternalHosts”下面
添加一个值可能为“http://nqatalog.negroesquisso.pt”的条目。 我使用*仅用于调试目的。
这是我在尝试使用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
如果你正在编写一个Chrome扩展并得到这个错误,那么请确保你已经将API的基本URL添加到你的清单中。Json的权限块,例如:
"permissions": [
"https://itunes.apple.com/"
]