I am doing an AngularJS project right now at http://localhost with the laravel backend at http://api.localhost , both served by the nginx server.
when executing the $ http.post request, angular first calls the CORS OPTIONS call, and I configured the nginx server to respond with the appropriate headers:
location / { add_header "Access-Control-Allow-Origin" "*"; add_header "Access-Control-Allow-Credentials" "true"; add_header "Access-Control-Allow-Methods" "GET,POST,DELETE,PUT,OPTIONS"; add_header "Access-Control-Allow-Headers" "Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type,Authorization"; add_header "Access-Control-Max-Age" "1728000"; if ($request_method = 'OPTIONS') { return 204; }
My angular module is also configured to:
.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; }])
The OPTIONS call returns as expected:
Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type,Authorization Access-Control-Allow-Methods:GET,POST,DELETE,PUT,OPTIONS Access-Control-Allow-Origin:* Access-Control-Max-Age:1728000 Connection:keep-alive Date:Mon, 04 Nov 2013 02:14:16 GMT Server:nginx/1.2.6 (Ubuntu)
But the subsequent POST call, which I am doing unsuccessfully, has the status CANCELED and angular throws a JS console error:
`XMLHttpRequest cannot load http://api.localhost/users/accesstokens. Origin http://localhost is not allowed by Access-Control-Allow-Origin.`
I lingered last night and got this job, but when I tried again today, he was back to square one. The worst problem!
What to do?
EDIT: I found the problem, but I still don't understand it. I looked at nginx access logs and saw that the POST request actually hit the server, although the status was CANCELED. I also saw that the answer was 401. After my request was correct, the answer was 201. However, the same status is CANCELED. But when I adjusted the status to 200, voila! The request worked as intended.
Is there a reason AngularJS only accepts status 200 in a cross start request?