Help with Angular rest service 4 Django Rest Framework

1

Good afternoon, I'm making an application using Django and Angular 4 however when I try to consume the service provided by django I get the following error.

  

Response to preflight request does not pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested   resource. Origin ' link ' is therefore not allowed   access.

The service is working perfectly for me, however, as the data arrives in the browser, although Angular 4 does not know how to understand the data

The code I have in Angular 4 is the following:

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


import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
// import 'rxjs/add/operator/toPromise';

import * as moment from 'moment';
import {Reserva} from "./reserva";
import {RESERVAS} from "./reserva.mock";

@Injectable()
export class ReservaService {

   private reservaUrl = 'http://127.0.0.1:8000/api/v1/reservas/';  // URL to web api
   constructor(private http: Http) { }




  getReservas(): Observable<Reserva[]>{

    /**
     * Servicio consumiendo los datos REST
     */

    // let headers = new Headers();
    // headers.append('Access-Control-Allow-Headers', 'Content-Type');
    // // headers.append('Access-Control-Allow-Methods', 'GET');
    // // headers.append("Access-Control-Allow-Headers", 'Origin, Content-Type, X-Auth-Token');
    // headers.append('Access-Control-Allow-Origin','http://127.0.0.1:8000');
    // // headers.append('Content-Type', 'application/json; charset=utf-8');
    // headers.append('Accept', 'application/json');
    // headers.append("Content-type", "application/x-www-form-urlencoded, application/json");
    // let options = new RequestOptions({ headers: headers});
    // return this.http.get(this.reservaUrl)
    //   .toPromise()
    //   .then(response => response.json().data as Reserva[])
    //   .catch(this.handleError)

      let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
      let options = new RequestOptions({ headers: cpHeaders });

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


  }

  private extractData(res: Response) {
     console.info("Los datos", res.json())
     let body = res.json();
     return body.data || { };
  }

  private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = '${error.status} - ${error.statusText || ''} ${err}';
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }




}

I have made different with the class Headers , but none works for me.

Please, if someone has this problem and can help me, it will be very helpful.

Thank you very much

    
asked by Duany 26.10.2017 в 19:57
source

1 answer

0

Thank you very much for your answer and you were absolutely right I was using these plugins but I still had to put the following classes in the settings in the MIDDLEWARE variable:

'corsheaders.middleware.CorsMiddleware',
'corsheaders.middleware.CorsPostCsrfMiddleware'

So the code I put in was correct. Thank you again. Sldos

    
answered by 27.10.2017 / 21:54
source