使用 Angular 8 HttpClient 和 Python Flask 时出现未知错误

Unknown Error when using Angular 8 HttpClient and Python Flask

我有一个 Python Flask 后端服务,它在 API 上使用 GET 调用时提供 JSON,如下所示:

查询:

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

回复:

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

我真的只想在通过 Angular

构建的前端下拉列表中显示列表

后端

代码片段:

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)

前端

我创建了一个服务:

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`);
    }
}

在组件中,我按如下方式调用服务:

component.ts

ngOnInit() {
  this.getBusinessLocations();
}

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

错误

究竟是什么导致了这个错误?与CORSHTTPS有关吗?我都没有,因为该应用程序仍在测试和开发中。 相反,我可以通过 Websockets

与后端通信

这个问题实际上是CORS相关的。

我使用以下方法解决了这个问题:

pip install flask-cors

然后在后端代码中:

 from flask_cors import CORS, cross_origin

 app = Flask(__name__)
 CORS(app)

这应该可以完全消除错误并且控制台能够记录后端的输出。