Django-rest交叉原始请求失败

时间:2017-07-21 08:37:12

标签: django angular django-rest-framework django-cors-headers

我已安装django-cors-headers,我的seetings.py有以下内容:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'rest_framework_docs',
    'tasks'
]

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.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

但是,当我从Angular前端点击网址时,我仍然会收到Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response错误。

我错过了任何配置吗?

3 个答案:

答案 0 :(得分:1)

您需要添加:

(def my-set
    ({:num 0}
     {:num 0}
     {:num 0}
     {:num 5}
     {:num 5}
     {:num 5}
     {:num 10}
     {:num 10}
     {:num 10}
))

也是你的settings.py,它会起作用;)

答案 1 :(得分:0)

问题不在后端,我的角度服务功能如下:

  getTasks(): Observable<Task[]> {

    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers });

    return this.http.get(this.taskUrl, options)
    .map(this.extractData)
    .catch(this.handleError);
  }

必须是:

  getTasks(): Observable<Task[]> {

    return this.http.get(this.taskUrl)
    .map(this.extractData)
    .catch(this.handleError);
  }

答案 2 :(得分:0)

在我的情况下,当backend(django)和frontend(angular)在同一主机上工作时,它可以工作。就像localhost:8000上的django服务器和localhost:4200上的angular服务器一样。