I hosted my client on localhost:8080/ and server on localhost:44302/
I am trying to link to my backend, but I am getting CORS issue. Below is my Angular http request
$http.post(url, data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS'
}
}).success(function (response) {
// rest of the code
}).error(function (err, status) {
// rest of the code
});
On the server side which is written in C#, I have the following set on the response
Response.ContentType = "application/json";
Response.AddHeader("Access-Control-Allow-Origin", "*");
Response.AddHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
Even after setting these, I am getting the following error
XMLHttpRequest cannot load https://localhost:44302/some_uri. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 400.
What am I missing?
You do not need to send any additional headers from AngularJS. Preflight request will be made for you automatically.
To enable all cross-origin requests in Web API, you can do this:
Add the following code to WebApiConfig.cs:
Full understanding of CORS is worth a few minutes of time. I recommend reading an in-depth tutorial here:
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api