[英]Access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]django & javascript fetch(): CORS policy: No 'Access-Control-Allow-Origin' header is present
我正在尝试拨打 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 存在于请求的资源上。 如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
(索引):798 GET http://sub.example.com/net ::ERR_FAILED
跨域读取阻塞 (CORB) 阻止了 MIME 类型为 text/plain 的跨域响应http://sub.example.com/ 。 有关详细信息,请参阅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
和我的 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',
...
]
如果我用例如 Insomnia 测试它,我从服务器获得的原始响应数据是:
{"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',
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.