Search code examples
djangoangularjscorstastypiedjango-cors-headers

Perform an ajax call from AngularJS to a Django server that allows CORS


I am developing a webapp using AngularJS and a REST API based on Django-Tastypie to get data.

To be able to perform ajax requests, I enabled Cross Origin Resource Sharing on django using django-cors-header framework (https://github.com/ottoyiu/django-cors-headers), but I noticed in chrome inspector that the preflighted request (an OPTIONS request) that is sent before the main request is cancelled almost immediately and I saw in the Django server logs this : "OPTIONS /api/airport/19643 HTTP/1.1" 301

I found some posts about this suggesting to delete a the 'X-Requested-With' parameter from the header ($http.get is not allowed by Access-Control-Allow-Origin but $.ajax is) but this resolves the problem only for GET requests. So if I try to send a PUT or POST request, a preflighted request is sent and gets cancelled !

Here is the what I see on the inspector when I enable CORS but don't delete the previous parameter from the header: enter image description here

I get the same error for PUT requests as well.

I can't really see where the problem is, so I hope if someone could point me to the right direction.

Thanks a lot


Solution

  • Well the problem was a missing / in the URL. So instead of sending an ajax request to : /api/airport/19643, I should've used /api/airport/19643/ (weird...)

    (for more details about CORS, I recommand you to see https://developers.google.com/storage/docs/cross-origin )