Search code examples
pythonangularflaskangular-httpclient

Unknown Error when using Angular 8 HttpClient and Python Flask


I have a Python Flask Backend Service which provides a JSON when using a GET call on the API as follows:

Query:

curl -XGET http://localhost:5000/bizLocations

Response:

{
  "data": {
    "locations": [
      "urn:epc:id:sgln:bizLocation.Location.1",
      "urn:epc:id:sgln:bizLocation.Location.2",
      "urn:epc:id:sgln:bizLocation.Location.3"
    ]
  }
}

I really just want to display the list in a Drop-Down List for Frontend built via Angular

Backend

Code Snippet:

from flask import Flask, jsonify

# .. 

bizLocations = {
    'data': {
        'locations':
        [
            'urn:epc:id:sgln:bizLocation.PodComp.1',
            'urn:epc:id:sgln:bizLocation.PodComp.2',
            'urn:epc:id:sgln:bizLocation.PodComp.3'
        ]
    }
}

@app.route('/bizLocations', methods=['GET'])
def get_biz_locations():
    return jsonify(**bizLocations)

Frontend

I created a service:

component.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ComponentService {

    private backEnd = 'http://localhost:5000';

    constructor(private http: HttpClient) { }

    getBizLocations() {
        return this.http.get(`${this.backEnd}/bizLocations`);
    }
}

Within the Component I call the service as follows:

component.ts

ngOnInit() {
  this.getBusinessLocations();
}

getBusinessLocations() {
        this.componentService.getBizLocations()
            .subscribe((data: any) => {
                console.log(data);
                this.locations = data.locations;
            });
    }

Errors

Error Log in Console

What is actually causing this error? Is it something to do with CORS or HTTPS? I have neither of them as the app is still under testing and development. On the contrary I am able to communicate with the backend via Websockets


Solution

  • This problem is actually CORS related.

    I solved this using:

    pip install flask-cors
    

    and then in the backend code:

     from flask_cors import CORS, cross_origin
    
     app = Flask(__name__)
     CORS(app)
    

    This should remove the Error completely and the console was able to log the output from the backend.