简体   繁体   English

在Django Apache专案中启用CORS

[英]Enable CORS in a Django Apache Project

I have an Django project that runs on Apache. 我有一个在Apache上运行的Django项目。 With Javascript and Python i make request on diffrent sites. 使用Javascript和Python,我可以在不同的站点上发出请求。 I always get following error: 我总是收到以下错误:

Access to XMLHttpRequest at 'site' from origin 'site2' has been blocked

I already tried diffrent things. 我已经尝试过其他事情。 I installed django-cors-headers and edited my files: 我安装了django-cors-headers并编辑了文件:

Settings.py: Settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'webpack_loader',
    'corsheaders',
    'projects',
    'viewer',
    'api_manager',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

In my HTML i added following to the form: 在我的HTML中,我在表单中添加了以下内容:

<form class="d-flex flex-column" id="loginForm">
          {% csrf_token %}
</form>

With the following method i was able to get a CSRF Token: 通过以下方法,我能够获得CSRF令牌:

static getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      let cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i].trim();
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

And the call which needs CORS i already tried to add the correct Headers: 并且需要CORS的呼叫我已经尝试添加正确的标头:

xhr.addEventListener('readystatechange', function () {
    if (this.readyState === 4) {
      if (this.status != 200) {
        console.log("Error", this.statusText);
      }
    }
  });

  xhr.onerror = function(e) {
    console.log("Error: " + e + "URL: " + url);
  }

  xhr.open(method, url, false);
  xhr.setRequestHeader('Authorization', auth);
  xhr.setRequestHeader('Content-Type', 'application/json');
  // xhr.setRequestHeader('Access-control-allow-origin', '*');
  xhr.setRequestHeader('Access-Control-Allow-Origin', '*');

  var token = Fetcher.getCookie('csrftoken');
  console.log(token);
  xhr.setRequestHeader('X-CSRFToken', token);
  xhr.send(data);

I dont know what I am missing. 我不知道我在想什么。 Does anyone know what i need to edit? 有人知道我需要编辑什么吗?

将其添加到settings.py文件的末尾。

CORS_ORIGIN_ALLOW_ALL = True

Add these things, in your settings.py file as follows (if you haven't added yet)... 如下所示在您的settings.py文件中添加这些内容(如果尚未添加)...

CORS_REPLACE_HTTPS_REFERER      = True
HOST_SCHEME                     = "https://"
SECURE_PROXY_SSL_HEADER         = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT             = True
SESSION_COOKIE_SECURE           = True
CSRF_COOKIE_SECURE              = True
SECURE_HSTS_INCLUDE_SUBDOMAINS  = True
SECURE_HSTS_SECONDS             = 1000000
SECURE_FRAME_DENY               = True

May be it'll work for you. 可能对您有用。 And, as you've added corsmiddleware to the middlewares you may check this guide once: django-cors-headers . 并且,由于您已将corsmiddleware添加到中间件中,因此您可以查看一下本指南: django-cors-headers Also, you can try with... 另外,您可以尝试...

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]
CORS_ORIGIN_REGEX_WHITELIST = [
    r"^https://\w+\.example\.com$",
]

Update with jquery... 用jQuery更新...

$(document).ready(function() {
    function getCookie(c_name) {
        if(document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=")
            if(c_start != -1) {
                c_start = c_start + c_name.length + 1
                c_end = document.cookie.indexOf(";", c_start)
                if(c_end == -1) c_end = document.cookie.length
                return unescape(document.cookie.substring(c_start,c_end))
           }
       }
       return ""
    }

    var csrfToken = getCookie('csrftoken')

    function csrfSafeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method))
    }

    $(function () {
        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader('X-CSRFToken', csrfToken)
                    xhr.setRequestHeader('Access-Control-Allow-Origin', '*')
                    xhr.withCredentials = true
                }
            }
        })
        // .done(function (data) { *do something* })
        // .fail(function () { *do something* })
    })
 })

I'm not sure though, either it'll work for you or not, but you can try. 不过,我不确定,它是否对您有用,但是您可以尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM