[带有Django和Angular的CORS预检请求

问题描述 投票:2回答:3

我很想向REST API发出请求。这是CORS要求。我的前端:Angular 1.5(localhost:3000)我的后端:Django(*****。ddns.net)

因此,我正在使用一种服务(由不希望共享代码的人(:)提供,即在实际请求(预检)之前执行OPTIONS请求。确切地说,该调用是通过解决方案进行的UI路由器状态定义的选项。Django的CORS允许*。

这是我在谷歌浏览器中收到的错误:

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.

如果我在控制器中执行经典的$ http请求,则它正在工作。

这是我的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

这是我与邮递员一起收到的回复(当我执行OPTIONS请求时,它与邮递员一起工作)

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

我认为这是Django方面的问题,我不知道。如果您有任何想法...(我需要学习很多有关CORS的信息...)

javascript angularjs django cors preflight
3个回答
4
投票
请确保您要定位的URL的构造正确,并且所呼叫路由的末尾有斜杠。如前所述here。所以代替这个

1
投票
这可能是因为不允许您发送的某些标头。为了确保这一点,只需转到Google chrome调试器并复制请求标头,然后使用邮递员发送即可。如果失败,请清除标题,直到找出不允许使用的标题为止。

0
投票
我最终为Django 2编写了一个小型中间件:
© www.soinside.com 2019 - 2024. All rights reserved.