Access-Control-Allow-Origin不允许使用origin http:// localhost:1716

我有这个错误

XMLHttpRequest无法加载http://localhost:81/Test/Service.svc/SetJSON 。 Access-Control-Allow-Origin不允许使用http://localhost:1716

当我使用jquery调用wcf web服务时。

 $.ajax({ type: 'POST', url: webmethod, data: '{"data":"Darshana"}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert(msg.d); }, error: function (e) { alert("Unavailable"); } }); 

这是为什么?

任何帮助。 感谢名单..

基本上,因为您访问的是不同的端口,所以它不在同一个源上 。

您需要在端口1716上运行的服务上启用跨源资源共享。

不知道你想要做什么,这样的配置:

           

应该允许您进行测试,但是对于生产,建议将适当的域列入白名单而不是使用通配符。

不同的端口,尝试设置dataType: 'jsonp'

我通过Apache mod_proxy模块解决了这个问题。 启用模块:

 LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so 

然后加:

 ProxyPass /your-get-url/ http://localhost:1716/ 

最后,将proxy-url传递给您的脚本。

我不记得我是怎么得到这个错误的。 但是,由于很多人都有这个问题我想发布我所做的。

WCF – IService

 [OperationContract] [WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "SetJSON?data={data}")] string SetJSON(string data); 

WCF – 服务

 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service : IService { public string SetJSON(string data) { return data; } } 

WCF – web.config

       ....      

Jquery电话

 $.ajax({ type: "GET", url: "http://localhost:81/Test/Service.svc/SetJSON?data=" + "{ \"dl\":" + datalist + " }", contentType: "application/json; charset=utf-8", dataType: "jsonp", success: function (data) { alert(data.toString()); }, error: function (XMLHttpRequest, textStatus, errorThrown) { debugger; alert("Error Occured!"); } }); 

不是100%肯定什么解决了我的问题。 无论如何,这将有助于某人。 🙂

如果你在Angular.js中使用localhost:port,那么请确保你像这样转义你的端口号:

 var Project = $resource( 'http://localhost\\:5648/api/...', {'a':'b'}, { update: { method: 'PUT' } } ); 

有关它的更多信息,请参阅https://github.com/angular/angular.js/issues/1243 。

我写了一篇博文(不允许从“本地”数据源访问JSON数据) ,这本质上是zenio的解决方案,但是有逐步指导。 您在Apache中设置了反向代理,以便将本地URL转发到承载JSON数据的端口(基本上,将其转发到“远程”数据源)。