NOaMTL
NOaMTL

Reputation: 193

CORS preflight request with Django and Angular

I ham trying to make a request to a REST api. It is a CORS request. My frontend : Angular 1.5 (localhost:3000) My Backend : Django (*****.ddns.net)

So I am using a service ( made by someone who doesn't want to share the code :( ), that is doing a OPTIONS request before the real request (preflight). To be precise, the call is made through the resolve option of UI-router state definition. Django has CORS to allow *.

This is the error that i get in google chrome :

XMLHttpRequest cannot load https://****.net/api/myprofile. The request was redirected to 'https://*****.net/punchclock/api/myprofile/', which is disallowed for cross-origin requests that require preflight.

If I do a classic $http request in a controller, it is working.

This is the request recieved my django :

+6655:5740d0f9:10|
OPTIONS /punchclock/api//myprofile HTTP/1.0|
Host:*****.net|
Connection:close|
Pragma:no-cache|
Cache-Control:no-cache|
Access-Control-Request-Method:GET|
Origin:http%3a//localhost%3a3000|
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36|
Access-Control-Request-Headers:accept, authorization|
Accept:*/*|
Referer:http%3a//localhost%3a3000/dashboard|
Accept-Encoding:gzip, deflate, sdch|
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,es;q=0.2
-6655:5740d0f9:10

And this is the response i get if I do it with postman (it is working with postman when i do an OPTIONS request)

Access-Control-Allow-Headers →x-requested-with, content-type, accept, origin, authorization, x-csrftoken
Access-Control-Allow-Methods →GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Origin →*
Access-Control-Max-Age →86400
Allow →GET, HEAD, OPTIONS
Connection →keep-alive
Content-Type →application/json
Date →Sat, 21 May 2016 21:15:02 GMT
Server →nginx/1.6.2
Transfer-Encoding →chunked
Vary →Accept
X-Frame-Options →SAMEORIGIN

I think it is an issue on Django's side, I don't know. If you have any idea... (I need to learn a lot about CORS...)

Upvotes: 1

Views: 11057

Answers (2)

user42488
user42488

Reputation: 1455

Make sure the URL you are targeting is correctly constructed and that there is a trailing slash at the end of the route you are calling. As mentioned here. So instead of this

'http://localhost:5000/auth'

you would call this

'http://localhost:5000/auth/'

Hope this helps.

Upvotes: 5

It is probably because some of the headers you are sending are not allowed. To make sure, just go to google chrome debugger and copy the request headers and send them using postman. If it fails eliminate the headers until you find out which one is not allowed.

There is a similar answer here that may help. Specifically where it says

According to the W3 CORS Spec Section 6.2 Preflight Requests, the preflight must reject the request if any header submitted does not match the allowed headers.

Upvotes: 1

Related Questions