我目前正在使用线程标题中提到的技术开展项目.
我从浏览器运行它(应用程序托管在heroku上),但是当我尝试从Ionic 2应用程序连接到websockets时,我总是在建立握手时出错.
2016-09-17T15:02:03.200133+00:00 app[web.1]: 2016-09-17 15:02:03,199 DEBUG Connection http.response!uvRVDyvolYEG did not get successful WS handshake.
2016-09-17T15:02:03.200498+00:00 app[web.1]: 2016-09-17 15:02:03,200 DEBUG WebSocket closed before handshake established
2016-09-17T15:02:03.169206+00:00 heroku[router]: at=info method=GET path="/1/" host=musicmashup-jukebox.herokuapp.com request_id=c46960d7-bb8f-45bf-b8be-5a934c771d96 fwd="212.243.230.222" dyno=web.1 connect=0ms service=7ms status=400 bytes=74
Run Code Online (Sandbox Code Playgroud)
现在有一个想法是,它可能是一个CORS问题.所以我安装django-cors-middleware希望这可以解决问题 - 好吧它没有.但我认为应用程序根本不会向Daphne服务器添加任何标头.
目前我不知道,如果问题出在客户端或服务器端.
有没有人遇到类似的问题?
编辑:发现websockets和CORS彼此没有任何关系为什么WebSockets没有同源策略?为什么我可以连接到ws:// localhost? 所以我的猜测是,服务器可能会拒绝客户端发送的原始标头.我会看看我是否可以抓住发送的标题
django django-rest-framework ionic-framework django-cors-headers django-channels
因此,我将django-cors-headers与带有Django 1.11.x的Rest Framework一起使用,并且我已经大致遵循了一般建议,但是,我仍然x has been blocked by CORS policy: No 'Access-Control-Allow-Origin'在请求的资源上使用header。”可以看到,我已经在INSTALLED_APPS和'corsheaders.middleware.CorsMiddleware'上添加了“ corsheaders” Middleware,并且我也将其设置CORS_ORIGIN_ALLOW_ALL为true和CORS_ALLOW_CREDENTIALStrue。甚至包括白名单选项,尽管据我了解,如果CORS_ORIGIN_ALLOW_ALL将其设置为true,白名单是不需要的,我也有pip3 install django-cors-headers什么关系???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????就必道之·,我已经阅读了django-cors-headers仓库中的自述文件,我想知道为什么它不起作用。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'books.apps.BooksConfig',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = (
'localhost:5555'
)
Run Code Online (Sandbox Code Playgroud)
从本地主机:5555访问的我的js文件是:
var request = $.ajax({
type: 'GET',
url: url,
dataType: 'json',
xhrFields: {
withCredentials: true
}});
Run Code Online (Sandbox Code Playgroud) 我正在开发一个使用 Django-rest-framework 服务的 ExtJS 应用程序。我正在使用 CORS 标头来允许从服务 ( https://github.com/OttoYiu/django-cors-headers )获取数据。
发生的情况是,我想在某个时间点更改商店中的 URL。当我这样做时,我收到以下错误:
XMLHttpRequest cannot load http://10.98.0.241:8000/reacsearch/as?_dc=1418831884352&page=1&start=0&limit=25. The request was redirected to 'http://10.98.0.241:8000/reacsearch/as/?_dc=1418831884352&page=1&start=0&limit=25', which is disallowed for cross-origin requests that require preflight.
Run Code Online (Sandbox Code Playgroud)
在 settings.oy 中,我为 CORS 定义了以下属性
CORS_ALLOW_METHODS = (
'GET',
'OPTIONS'
)
CORS_ORIGIN_ALLOW_ALL = True
Run Code Online (Sandbox Code Playgroud)
当我使用 URL 列出数据库中的所有元素时,这很好用,但是当我将存储更改为另一个 URL 时,我收到上述错误。该链接在浏览器中也能正常工作。
商店网址更改是这样进行的:
var store = Ext.getStore(storeName);
store.getProxy().setUrl(newURL);
store.load();
Run Code Online (Sandbox Code Playgroud)
视图之间的区别在于,在应用程序上工作的两个是视图集,而另一个只是一个通用列表
class Example1viewset(viewsets.ModelViewSet):
"""
API endpoing that allows metabolites to be viewed.
"""
queryset = examples1.objects.all()
serializer_class = Example1Serializer
class Example1SearchList(generics.ListAPIView):
serializer_class = …Run Code Online (Sandbox Code Playgroud) 我已经在Django中使用"django-cors"启用了CORS:
https://github.com/ottoyiu/django-cors-headers
按照此处的安装步骤后,我设置了以下内容:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:8000'
)
Run Code Online (Sandbox Code Playgroud)
django应用程序在http:// locahost:3000上运行
我的前端是一个Angular应用程序,它运行在"http:/ localhost:8000"上,我已经完成了以下更改以与django应用程序进行通信.
RestangularProvider.setBaseUrl('http://localhost:3000/');
Run Code Online (Sandbox Code Playgroud)
[为资源API使用Restangular]
当我调用GET API时,会发生"OPTIONS"飞行前调用,并且出现以下错误:
XMLHttpRequest无法加载http:// localhost:3000/users.凭据标志为"true",但"Access-Control-Allow-Credentials"标头为"".允许凭据必须为"true".因此不允许来源' 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, …Run Code Online (Sandbox Code Playgroud) 我试图让CORS请求正常工作.使用以下JS代码,我收到此错误:XMLHttpRequest cannot load http://localhost:65491/?token=u80h9kil9kjuu02539buak4r6n&user=~me. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:50303' is therefore not allowed access.
这是JS代码:
$.ajax({
url: "http://localhost:60906/",
data: {token : 'u80h9kil9kjuu02539buak4r6n', user : '~me'},
type: "GET",
crossDomain: true,
success: function( response ) {
alert('Success!' + response);
var context = response;
}
});
Run Code Online (Sandbox Code Playgroud)
当我使用chrome的devtools查看网络时,我发现'Access-Control-Allow-Origin'确实没有标头.但是当我手动加载网站时它就存在了!
我使用以下代码来设置标头:
response = JsonResponse(simpleWeek)
response['Access-Control-Allow-Origin'] = '*'
return response
Run Code Online (Sandbox Code Playgroud)
希望得到一些帮助!
我的Django静态文件有问题。我正在使用Django admin和Django Rest Framework。我正在尝试使用S3存储桶为admin和DRF提供静态文件。我可以成功访问存储桶中任何文件的URL,它将在我的浏览器中加载,并且该文件通过HTTPS提供。
我在CloudFormation中为S3存储桶创建了一个嵌套堆栈:
Description: >
This template deploys S3 buckets for serving Django static files.
Parameters:
AppUrl:
Type: "String"
Description: "The URL for our app (e.g. mydomain.com)"
AllowedPattern: "[a-z0-9._-]+"
Resources:
AssetsBucket:
Type: "AWS::S3::Bucket"
Properties:
BucketName: !Sub ${AppUrl}-assets
AssetsBucketPolicy:
Type: "AWS::S3::BucketPolicy"
Properties:
Bucket: !Ref AssetsBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: PublicReadForGetBucketObjects
Effect: "Allow"
Principal: "*"
Action: "s3:GetObject"
Resource: !Sub "${AssetsBucket.Arn}/static/*"
Run Code Online (Sandbox Code Playgroud)
当我的应用程序启动时,它将运行collectstatic,并将静态文件移入存储桶。这是我遇到的问题:
当我访问带有查询参数的DRF URL时?format=json。这将返回一个JSON响应,没有来自可浏览API的静态文件,并且我看不到任何错误。但是,当我访问可浏览的API或管理界面时,我似乎发现了三个错误消息之一。在Chrome中,我看到的是两种类型的行为。HTTPS已从URL中剥离(以红色划线),但是在静态资产加载时,控制台中显示了以下两个错误之一:
Access to font at 'https://mydomain.com-assets.s3.amazonaws.com/static/admin/fonts/Roboto-Bold-webfont.woff' from origin 'https://api.mydomain.com' has …Run Code Online (Sandbox Code Playgroud) 相关信息:Django 版本 2.2
\n我已安装django-cors-headers并将其添加到启用的应用程序中,并将中间件作为第一个中间件添加到中间件设置中。
我还配置了设置:
\n\nINSTALLED_APPS = [\n ...\n "corsheaders",\n "rest_framework",\n "django.contrib.admin",\n ...\n]\n\n\nMIDDLEWARE = [\n ...\n "corsheaders.middleware.CorsMiddleware",\n "django.contrib.sessions.middleware.SessionMiddleware",\n "django.middleware.common.CommonMiddleware",\n ...\n]\n\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_ALLOW_CREDENTIALS = True\nRun Code Online (Sandbox Code Playgroud)\n我的设置有 2 个项目在不同的端口上运行。Django 服务器运行在 8000 上,我的前端运行在 8080 上。
\n前端发送的所有 API 请求都可以正常工作。但是当我尝试加载后端项目提供的 one.js 文件时,它失败并出现以下错误:
\n\nCross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/static/myscript.js. (Reason: CORS header \xe2\x80\x98Access-Control-Allow-Origin\xe2\x80\x99 missing)\n\nRun Code Online (Sandbox Code Playgroud)\n我加载脚本的方式是创建一个新的脚本元素,并将 URL 添加http://127.0.0.1:8000/static/myscript.js为脚本标记上 src 属性的值。
https://code.jquery.com/jquery-3.5.1.min.js当我使用像而不是这样的值时,不会发生此错误,http://127.0.0.1:8000/static/myscript.js因此看起来 Django runserver 提供的静态文件存在一些问题,但具体是什么以及为什么超出了我的范围。 …
我正在尝试使用 Django 制作一个简单的 API。我已经设置了一个 django 服务器,然后在我自己的 html 文件上使用$.getJSON. 到目前为止,它一直在使用django cors headers package进行工作。
现在我一直在尝试将请求标头发送到我的 django 服务器,但我在 Chrome 控制台中收到此错误:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/?q=example+query' from origin 'http://localhost:63342' has been blocked by CORS policy: Request header field Example-Header is not allowed by Access-Control-Allow-Headers in preflight response.
Run Code Online (Sandbox Code Playgroud)
我不确定问题是什么,我的 django-cors 设置正确并且我能够发出请求,只是不允许设置请求标头。
设置:
INSTALLED_APPS = [
...
'corsheaders',
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:63342"
]
Run Code Online (Sandbox Code Playgroud)
<script>
$.ajaxSetup({
beforeSend: function(request) {
request.setRequestHeader("Example-Header", 'Example-Value');
},
});
$.getJSON("http://127.0.0.1:8000/api/?q=example+query", …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用django-cors-headers将COR添加到我的服务器,但是当我加载页面时,我在服务器上收到此错误.
ImproperlyConfigured: Error importing module corsheaders.middleware.CorsMiddlewaredjango.middleware.common: "No module named CorsMiddlewaredjango.middleware.common"
Run Code Online (Sandbox Code Playgroud)
我已经使用pip安装了cors-header app:
pip install django-cors-headers
Run Code Online (Sandbox Code Playgroud)
我的settings.py文件以这种方式配置:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social.apps.django_app.default',
'corsheaders',
'dashboard',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware'
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
CORS_ORIGIN_ALLOW_ALL = True
Run Code Online (Sandbox Code Playgroud)
我正在使用python 2.7版本.
我面临的问题是我无法从 NextJS 前端获取现有用户。我使用的后端框架是 Django(以及 django-cors-headers 包)。django-cors-headers 不允许某个 HTTP 请求,但它应该允许。
\n我的 next.config.js 包含重写,以便我可以访问我的后端。
\nasync redirects() {\n return [\n {\n source: \'/api/:path*\',\n destination: \'http://localhost:8000/:path*/\',\n permanent: true,\n },\n ]\n },\nRun Code Online (Sandbox Code Playgroud)\n我的 django-cors-headers 设置如下所示:
\n# CORS\n\nCSRF_TRUSTED_ORIGINS = [\n \'http://localhost:3000\',\n]\n\nCORS_ALLOWED_ORIGINS = [\n \'http://localhost:3000\',\n \'http://localhost:8000\',\n \'http://127.0.0.1:3000\',\n \'http://127.0.0.1:8000\',\n]\n\nCORS_ALLOW_ALL_ORIGINS = True\nRun Code Online (Sandbox Code Playgroud)\n失败的请求尝试获取 ID 为 1 的用户。该用户存在,因此该请求应该成功。
\nfetch(`/api/users/${String(userId)}/`, {\n mode: \'cors\',\n credentials: \'include\',\n headers: {\n \'Content-Type\': \'application/json\',\n },\n })\nRun Code Online (Sandbox Code Playgroud)\n但是,我从请求中得到的唯一结果是有关 CORS 的错误消息。
\nCross-Origin Request Blocked: The Same Origin Policy disallows reading …Run Code Online (Sandbox Code Playgroud)