django & javascript fetch(): CORS policy:不存在'Access-Control-Allow-Origin'标头



我正在尝试进行ajax调用。我正在使用django 2.2.5cors 3.1.0,但在浏览器控制台中收到以下错误消息:

(索引(:1 从源头获取"http://sub.example.com/"的访问 "http://127.0.0.1:8000"已被 CORS 策略阻止:否 "访问控制允许源"标头存在于请求的上 资源。如果不透明响应满足您的需求,请将请求的 模式为"no-cors",以在禁用 CORS 的情况下获取资源。

(索引(:798 获取 http://sub.example.com/净::ERR_FAILED

跨源读取阻塞 (CORB( 阻止的跨源响应 http://sub.example.com/MIME类型的文本/纯文本。看 https://www.chromestatus.com/feature/5629709824032768 了解更多信息 详。

我的 ajax 调用如下所示:

setInterval(function() {
fetch('http://my.domain.com/')
.then(response => response.json())
.then(json => myHtmlTag.innerText = json.data)
}, 5000 );

我已经安装了django-cors-headers,我的 djangosettings.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

您可以在此处查看 CORS 如何在您的浏览器上工作。

在您的情况下,您可以将CORS_ORIGIN_WHITELIST更改为以下内容:

CORS_ORIGIN_WHITELIST = [
'http://127.0.0.1:8000',
'http://any.host.want.to.allow.to.access.this.server.com',
]

相关内容