Laziale Laziale - 2 months ago 7
AngularJS Question

CORS Issue same controller, one method is ok, other one is not

Very strange error I'm experiencing.

I have two methods in controller which are called by angular js http get event.

First one works fine, second one is throwing CORS error, not sure how is that possible since both of them are in same controller.

This is the error I'm getting: enter image description here

These are the calls I'm doing in angularjs:

$http({
url: 'http://localhost:52876/api/Admin/GetLoanInfo',
method: "GET",
params: { loanID: querystringParam }
}).success(function (data, status) {
console.log(data);
$scope.LoanDetailsVM.LoanStatus = data.LoanStatus;
}).error(function (data, status) {
console.log(data);
});

$http({
url: 'http://localhost:52876/api/Admin/GetLoanCovenants',
method: "GET",
params: { loanID: querystringParam }
}).success(function (data, status) {
console.log(data);
}).error(function (data, status) {
console.log(data);
});


And the controller methods:

[HttpGet]
[Route("api/Admin/GetLoanInfo")]
public async Task<IHttpActionResult> GetLoanInfo(int loanID)
{

LoanApplication newApplication = null;
newApplication = db.LoanApplications.FirstOrDefault(s => s.LoanId == loanID);
return Ok(newApplication);
}


[HttpGet]
[Route("api/Admin/GetLoanCovenants")]
public async Task<IHttpActionResult> GetLoanCovenants(int loanID)
{
LoanCovenant newCovenant = null;
newCovenant = db.LoanCovenants.FirstOrDefault(s => s.LoanID == loanID);
return Ok(newCovenant);
}


I'm able to hit both methods, I have breakpoints in both of the methods, but not sure why is complaining about CORS on the first one.

enter image description here

Answer

Calling methods using CORS from a Web browser makes Web API being called first with an OPTIONS request (example at the end of this article).

This way, the browser knows if it can call the requested API.

In your case, the call to your endpoint seems to be crashing, which means the HTTP 500 error does not contain any CORS headers.

This explains why the web browser complaning about CORS HTTP Header missing: Reason: CORS Header 'Access-Control-Allow-Origin' missing.

If you fix your method, then HTTP OPTIONS should be ok, and the CORS erros would go away.