【发布时间】:2016-03-23 20:19:15
【问题描述】:
我在 Django 中启用了 CORS,使用“django-cors”:
https://github.com/ottoyiu/django-cors-headers
按照这里的安装步骤,我设置了以下内容:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:8000'
)
django 应用在http://locahost:3000 上运行
我的前端是一个 Angular 应用程序,它在“http:/localhost:8000”上运行,我做了以下更改以与 django 应用程序通信。
RestangularProvider.setBaseUrl('http://localhost:3000/');
[将 Restangular 用于资源 API]
当我调用 GET API 时,会发生“OPTIONS”飞行前调用,并且我收到以下错误:
XMLHttpRequest 无法加载 http://localhost:3000/users。 Credentials 标志为“true”,但“Access-Control-Allow-Credentials”标头为“”。必须为“true”才能允许凭据。 Origin 'http://localhost:8000' 因此不允许访问。
查看文档,我了解到我需要设置服务器期望作为调用一部分的某些标头。所以,我添加了以下内容: RestangularProvider.setDefaultHeaders({"x-requested-with" : 'XMLHttpRequest'});
但是,在进行此更改时,我遇到了另一个错误,我无法解决: XMLHttpRequest 无法加载 http://localhost:3000/users。预检响应无效(重定向)
注意:请求/响应头如下:
General:
Remote Address:127.0.0.1:3000
Request URL:http://localhost:3000/users
Request Method:OPTIONS
Status Code:301 MOVED PERMANENTLY
Response Headers
Access-Control-Allow-Headers:x-requested-with, content-type, accept, origin, authorization, x-csrftoken, user-agent, accept-encoding
Access-Control-Allow-Methods:GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Origin:http://localhost:8000
Access-Control-Max-Age:86400
Content-Type:text/html; charset=utf-8
Date:Thu, 17 Dec 2015 11:10:16 GMT
Location:http://localhost:3000/users/
Server:WSGIServer/0.1 Python/2.7.10
X-Frame-Options:SAMEORIGIN
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, x-requested-with
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:3000
Origin:http://localhost:8000
Pragma:no-cache
Referer:http://localhost:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
【问题讨论】:
标签: angularjs django cors django-cors-headers