我正在尝试进行 ajax 调用。我正在使用 django 2.2.5
和 cors 3.1.0
,但在浏览器控制台中收到以下错误消息:
(index):1 Access to fetch at 'http://sub.example.com/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
(index):798 GET http://sub.example.com/ net::ERR_FAILED
Cross-Origin Read Blocking (CORB) blocked cross-origin response http://sub.example.com/ with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details.
我的 ajax 调用如下所示:
setInterval(function() {
fetch('http://my.domain.com/')
.then(response => response.json())
.then(json => myHtmlTag.innerText = json.data)
}, 5000 );
我已经安装了 django-cors-headers
,我的 django settings.py
看起来像这样,但无论如何它都不起作用:
CORS_ORIGIN_WHITELIST = [
'http://my.domain.com/',
]
CSRF_TRUSTED_ORIGINS = [
'http://my.domain.com/',
]
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
INSTALLED_APPS = [
'corsheaders',
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
...
]
原始响应数据,如果我使用例如测试它,我会从服务器获得该数据。失眠是:
{"data":"0123456789"}
最佳答案
您必须在允许的来源中添加请求者。在您的情况下,您应该添加 http://localhost:8000
关于javascript - Django 和 JavaScript fetch() : CORS policy: No 'Access-Control-Allow-Origin' header is present,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58059650/