0
  1. I have Angular2 as frontend and Django as backend. I am getting error for making a call to Django using services.
    1. Below is My Service method. Django is running on my local PC.

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

import { Observable } from 'rxjs/Observable';
import "rxjs/Rx"; 
import 'rxjs/add/operator/map';

import { Publisher } from './publisher';

@Injectable() 
export class PublisherService{
    
        
    constructor(private http: Http){
        
    }
    
    private getPubUrl = 'http://127.0.0.1:8000/api/v1/publisher';
    
    
    getPublishers(): Observable<Publisher[]>{
               
        return this.http.get(this.getPubUrl)
                        .map(this.extractData)
                        .catch(this.handleError);
    }
    
    private extractData(res: Response){
        console.log(res);
        let body = res.json();
        return body.data || { };
    }
    
    
    private handleError(error: any){
        let errMsg = (error.message) ? error.message : 
                     error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        return Observable.throw(errMsg);               
    }
}
  1. I am getting error XMLHttpRequest cannot load http://127.0.0.1:8000/api/v1/publisher. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
    1. Server Error
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Abhishek Sharma
  • 1,420
  • 1
  • 20
  • 30
  • http://stackoverflow.com/questions/10143093/origin-is-not-allowed-by-access-control-allow-origin This is not related to Angular. You need to configure your server to add required CORS headers. – Günter Zöchbauer Jul 19 '16 at 07:04
  • 1
    All you need to do is `CORS` whitelist your client in django backend. Install `django-cors-headers` and configure`CORS` in `settings.py`. See [here](http://stackoverflow.com/a/38188591/6522072) for more info. – kapilsdv Jul 19 '16 at 08:17
  • Thanks Kapil. It works fine now. – Abhishek Sharma Jul 20 '16 at 04:34
  • I got 16 points yesterday night. So i upvoted your answer and below one. – Abhishek Sharma Jul 21 '16 at 09:22

1 Answers1

0

if u are trying to access your backend from angular2 which runs on another port then u will have to allow cross origin calls (CORS)

JUST allow cors for localhost:3000 and this will be running perfectly fine :)

Akshay Rao
  • 3,454
  • 1
  • 15
  • 19
  • All you need to do is CORS whitelist your client in django backend. Install django-cors-headers and configureCORS in settings.py. See here for more info. (this you mean) – Abhishek Sharma Jul 20 '16 at 04:35