javascript - Django 和 JavaScript fetch() : CORS policy: No 'Access-Control-Allow-Origin' header is present

标签 javascript python django ajax cors

我正在尝试进行 ajax 调用。我正在使用 django 2.2.5cors 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/

相关文章:

javascript - 使用 HTML 和 Javascript 启用/禁用选项卡

javascript - 将鼠标悬停在父级元素上

python - 在python中提取定界符[]之间的单词

python - Django Rest 框架 token 认证

python - 构建我的 Django 第三方应用程序的最佳方式是什么

javascript - 寻找能量最高的结构

python - 更改 mlab quiver3d 和 surf 数据源而不清除特征脚本中的数字

python - App Engine 内存缓存异步操作 get_multi_async

python - Python Django 的多线程

javascript - Uncaught ReferenceError : require is not defined at add. js:1