Skip to content

Instantly share code, notes, and snippets.

@mk123
Last active September 21, 2020 16:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mk123/4e7709a4a720a458b4551b15c1077ccf to your computer and use it in GitHub Desktop.
Save mk123/4e7709a4a720a458b4551b15c1077ccf to your computer and use it in GitHub Desktop.
Angular 2 and django integration with CORS and cookies

How to enable cookies when using angular 2 and django rest framework.

To enable cross origin requests i.e. requests from different servers to django rest framwework api we need to use the following library.
Django CORS
The above link will tell you about most of the configurations but misses some of them which I think are specific to angular 2.

Assuming your django server is running on localhost:8000 and angular 2 server is running on localhost:4200 (your servers might be running on different ports so set accordingly, make following changes in setting.py file of your django project.

ALLOWED_HOSTS = ["127.0.0.1","localhost", ]

CORS_ORIGIN_WHITELIST = ( "127.0.0.1:4200", "localhost:4200", )

CORS_ALLOW_CREDENTIALS=True

CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT',)

CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Access-Control-Allow-Origin',)

Do not forget to add "Access-Control-Allow-Origin" to your CORS_ALLOW_HEADERS.

Following is the code of one of angular service file in one of my project which shows how to make a post request to a given url. The cookies received will be automatically handeled by the browser.

import { Injectable } from '@angular/core';
import { Headers,Http, Response } from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Injectable() export class CustomerService {

private loginUrl = 'http://127.0.0.1:8000/user/login'; private headers = new Headers({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'});

constructor(private http: Http) { }

login(details:string): Promise<string>{ return this.http.post(this.loginUrl,details,{headers:this.headers,withCredentials:true}) .toPromise().then(this.handleLoginResponse) .catch(this.handleError); } private handleLoginResponse(response: Response): Promise<string>{ console.log(response); return Promise.resolve(response.json()); } private handleError(error: any): Promise<string> { console.error('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); } }


Note carefully the two points.
  • The private variable headers contains the two properties.
  • In the "login" method, while making a post request to loginUrl, the code is sending one more argument i.e. withCredentials with headers. This argument allows cookies to be included in response.

I thing now your problem for communication of angular 2 with django rest api along with cookies is solved.

@leogout
Copy link

leogout commented Jan 24, 2020

Hello, thanks for this. Actually you can extend the default cors headers like so:

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = list(default_headers) + [
    'Access-Control-Allow-Origin',
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment