我在做一个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 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" );
}
其他回答
露比·辛纳屈
response['Access-Control-Allow-Origin'] = '*'
对每个人来说
response['Access-Control-Allow-Origin'] = 'http://yourdomain.name'
如果你有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>
当您收到请求时,您可以
var origin = (req.headers.origin || "*");
而当你不得不这样回答的时候:
res.writeHead(
206,
{
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': origin,
}
);
如果你正在编写一个Chrome扩展并得到这个错误,那么请确保你已经将API的基本URL添加到你的清单中。Json的权限块,例如:
"permissions": [
"https://itunes.apple.com/"
]
我会给你一个简单的解决方法。就我而言,我没有访问服务器的权限。在这种情况下,您可以更改您的谷歌Chrome浏览器的安全策略,以允许访问控制-允许起源。这很简单:
创建Chrome浏览器快捷方式 右键单击快捷方式图标->属性->快捷方式->目标
简单的粘贴到“C:\Program Files\谷歌\Chrome\Application\ Chrome .exe”——allow-file-access-from-files——disable-web-security。
位置可能不同。现在通过点击快捷方式打开Chrome。