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
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);
}
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.
What am I doing wrong?
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.
Remove this line,
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
from your getTasks()
function. You don't need to specify those options to the server. django-cors-headers
takes care of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With