我已经尝试了几天的django-cors-middleware,但是我只是不知道如何设置它。
谁能告诉我我做错了什么?
以下是我正在使用的测试项目设置。
- django-version:1.10.3
- python-version:3.5.2
- 项目名称:cors_test
- 应用程序名称:Appone
-
appone/urls.py
urlpatterns = [ url(r'^$', views.test_cors, name='test_cors'), ]
-
appone/views.py
def test_cors(request): return render(request, 'appone/test.html', {})
-
appone/templates/appone/test.html
<html> <script type="text/javascript"> var url = 'https://www.google.co.jp/?gfe_rd=cr&ei=BuxgWJ-_LIyL8QfIgYe4BQ'; var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onload = function() { var responseText = xhr.responseText; console.log(responseText); }; xhr.onerror = function() { console.log('There was an error!'); }; xhr.send(); </script> </html>
-
settings.py
INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appone' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True
就是这样!这就是每个设置,我通过
运行服务器python manage.py runserver
以下是我通过在上方运行
来获得的- 控制台的错误,
(索引):1 xmlhttprequest无法加载 https://www.google.co.jp/?gfe_rd=cr&ei = buxgwj-_liyl8qfigye4bq。不 请求的"访问控制"标头 资源。因此,不允许来源'http://127.0.0.1:8000' 使用权。
(索引):14错误!
请求标头
:authority:www.google.co.jp :method:GET :path:/?gfe_rd=cr&ei=BuxgWJ-_LIyL8QfIgYe4BQ :scheme:https accept:*/* accept-encoding:gzip, deflate, sdch, br accept-language:ja,en-US;q=0.8,en;q=0.6 cache-control:no-cache origin:http://127.0.0.1:8000 pragma:no-cache referer:http://127.0.0.1:8000/ user-agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 x-client-data:CJe2yQEIpbbJAQjEtskBCPucygEIqZ3KAQ==
响应标头
alt-svc:quic=":443"; ma=2592000; v="35,34" cache-control:private, max-age=0 content-encoding:gzip content-type:text/html; charset=UTF-8 date:Mon, 26 Dec 2016 10:48:37 GMT expires:-1 p3p:CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info." server:gws set-cookie:NID=93=Mg89hJyAP7FyVu5AT9RzCWxyPndiWPZdKTDgipYBJhJwEBRXdMLTa5aPOBvLjVW6mwUCY1qSaOnPPIlqMvT2x1VjdoPhdlyK67ufk5bOFJJC9eKaEtfngw2xWBhSTSyI; expires=Tue, 27-Jun-2017 10:48:37 GMT; path=/; domain=.google.co.jp; HttpOnly status:200 x-frame-options:SAMEORIGIN x-xss-protection:1; mode=block
常规
Request URL:https://www.google.co.jp/?gfe_rd=cr&ei=BuxgWJ-_LIyL8QfIgYe4BQ Request Method:GET Status Code:200 Remote Address:216.58.197.195:443
django-cors-middleware
应用程序允许您从不同域控制对Django应用的访问。它不允许您从Django应用程序控制对Google.co.jp的访问。您无法控制Google.co.jp返回的标题,因此您无法使用中间件启用CORS。
如果第三方不启用CORS或JSONP,则您无法使用JavaScript访问它。您必须在视图中获取内容。