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", ]Do not forget to add "Access-Control-Allow-Origin" to your CORS_ALLOW_HEADERS.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',)
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.
Hello, thanks for this. Actually you can extend the default cors headers like so: