I am new to angularjs and trying to consume wcf restful service using angularjs client.Initially I had tried for http.get(url) and got the CORS issue which I resolved by putting following code in my wcf service method which I want to call.
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", ""); WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS"); WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");*
Now when I made a post call (http.post) the same way I did for get I got the response back with out CORS issue.
But when I tried to pass JSON object while make a post I again started getting CORS issue.
My angular code for post is:
var requestData = {
RequestUserName: "Abc1",
RequestPass: "123"
};
var req = {
method: 'POST',
url: 'url',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: requestData
};
$http(req).success(function(){console.log("Success");
$scope.userDetails = response.UserNameAuthenticationResult;}).error(function(){console.log("Error");});
My WCF operation contract looks as below:
[WebInvoke(Method="POST",UriTemplate="/Authenticate"
,RequestFormat=WebMessageFormat.Json
,ResponseFormat=WebMessageFormat.Json
,BodyStyle = WebMessageBodyStyle.Wrapped)]
string UserNameAuthentication(Request request);
and method implementation is below:
public string UserNameAuthentication(Request request)
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
return "true";
}
And the error that I am getting is below:
**OPTIONS URL (anonymous function) @ angular.js:11442sendReq @ angular.js:11235serverRequest @ angular.js:10945processQueue @ angular.js:15552(anonymous function) @ angular.js:15568$eval @ angular.js:16820$digest @ angular.js:16636$apply @ angular.js:16928(anonymous function) @ angular.js:24551defaultHandlerWrapper @ angular.js:3398eventHandler @ angular.js:3386 localhost/:1 XMLHttpRequest cannot load http://localhost:8733/TestService/Login/Authenticate. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:14703' is therefore not allowed access. The response had HTTP status code 405.