Origin http://localhost:1716 is not allowed by Access-Control-Allow-Origin
Solution 1
I don't remember how I got this error and when. But, as lots of people having this problem I thought to post what I did.
WCF - IService
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "SetJSON?data={data}")]
string SetJSON(string data);
WCF - Service
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
public string SetJSON(string data)
{
return data;
}
}
WCF - web.config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP"
crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
....
<services>
<service name="RnDService.Service">
<endpoint address="" behaviorConfiguration="webHttpBehavior"
binding="webHttpBinding"
bindingConfiguration="webHttpBindingWithJsonP"
contract="RnDService.IService" />
</service>
</services>
Jquery call
$.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!");
}
});
not 100% sure what solved my problem. Anyway this will help someone. :)
Solution 2
Essentially, because you're accessing a different port it's not on the same origin.
You'll need to enable Cross Origin Resource Sharing on the service that runs on port 1716.
Without knowing what you're trying to do, a configuration like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Should allow you to test, although for production it's advisable to whitelist appropriate domains rather than using a wildcard.
Solution 3
Different port, trying setting dataType: 'jsonp'
Solution 4
I solved this by Apache mod_proxy module. Enable modules:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
Then add:
ProxyPass /your-get-url/ http://localhost:1716/
Finally, pass proxy-url to your script.
Comments
-
Darshana over 1 year
I have this error
XMLHttpRequest cannot load
http://localhost:81/Test/Service.svc/SetJSON
. Originhttp://localhost:1716
is not allowed by Access-Control-Allow-Origin.when I calls wcf web service using jquery.
$.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"); } });
why is that?
any help. thanx..