Django Angular Cors错误:不允许访问控制允许起源 [英] Django Angular cors error: access-control-allow-origin not allowed

查看:181
本文介绍了Django Angular Cors错误:不允许访问控制允许起源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用django-rest-auth在django应用中实现了auth。我在settings.py中的设置:

I have implemented auth in my django app using django-rest-auth. My settings in settings.py:

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'rest_auth.registration',
    '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',
]

ROOT_URLCONF = 'urls'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ALLOWED_HOSTS = ['*']

SITE_ID = 1

我是从前端登录的-我已收到令牌,并且我已将其存储在本地存储中。现在,我发出一个简单的GET请求,如下所示:

I am logged in from my frontend- I receieved a token with I have stored in my local storage. Now I making a simple GET request like following:

  getTasks(): Observable<Task[]> {

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

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

但这给了我: Request header field Access-在飞行前响应中,Access-Control-Allow-Header不允许使用Control-Allow-Origin。尽管我包括了凭据。

But it gives me : Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response. although I am including withCredentials.

我在做什么错了?

PS :如果我删除了POST,就没有错误,但是我得到的数据不正确,因为我的后端返回了特定用户的数据。

P.S: If I remove options from POST then there is no error but I get incorrect data because my backend returns data for a specific user.

推荐答案

删除此行,

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

来自 getTasks()函数。您无需为服务器指定这些选项。 django-cors-headers 会解决这个问题。

from your getTasks() function. You don't need to specify those options to the server. django-cors-headers takes care of that.

这篇关于Django Angular Cors错误:不允许访问控制允许起源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆