使用Python、Flask&角度



我正在使用Python、Flask&Angular在GCP(谷歌云平台(上遇到了一个与CORS相关的棘手问题。当我构建和服务前端时,我会得到以下错误:

访问'XMLHttpRequesthttps://jsonData-devshell.appspot.com/org'来自原点'https://mySPA-devshell.appspot.com'已被CORS策略阻止:请求的资源上不存在"Access Control Allow Origin"标头。

BACKEND

为了提供CORS,我导入了flask_CORS模块,并通过在我的服务器文件main.py.中添加CORS(app)将其添加到服务器文件中

main.py

from .entities.entity import Session, eco_env_engine, Base
from .entities.org import Org, OrgSchema
from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
# enable cross origin resource sharing
CORS(app)
Base.metadata.create_all(eco_env_engine)
@app.route('/org', methods=['GET'])
def get_org():
session = Session()
org_objects = session.query(Org).all()
# transform into JSON-serializable objects
schema = OrgSchema(many=True)
org = schema.dump(org_objects)
# serialize as json
session.close()
response = jsonify(org)
return response

我有一个shell脚本server.sh,它创建了一个我可以访问的接口http://0.0.0.0:5000.

server.sh


# set ../src/main.py as the value of the FLASK_APP environment variable
export FLASK_APP=../src/main.py
# FLASK_ENV=development
# FLASK_DEBUG=1
#activate the virtual environment
source $(pipenv --venv)/bin/activate
#run flask listening on all interfaces
#-h binds to interface
flask run -h 0.0.0.0

当我使用curl -I http://0.0.0.0:5000/org我得到

HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 4766
Access-Control-Allow-Origin: *
Server: Werkzeug/1.0.0 Python/3.7.3
Date: Wed, 01 Apr 2020 01:27:11 GMT

请注意Access Control Allow Origin:*标头,据我所知,它应该解决这个问题,但它没有。

我在GCP Cloud Shell编辑器中编写代码,并从GCP Cloud Shell终端中进行部署。为了让事情正常运行,我使用./server.sh &部署后端,使用ng serve部署前端

我尝试过的CORS变体:

CORS(app, resource={r'*/*': {'origins': '*/*'}})
CORS(app, resources={r"*": {"origins": ['https://mySPA-devshell.appspot.com', 'https://jsonData-devshell.appspot.com']}})
CORS(app, resources={r'*': {"origins": "*"}})
CORS(app, resources={r"*": {"origins": ['http://localhost:4200', 'http://localhost:5000']}})

前端

org-api.service.ts

import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
import {HttpHeaders, HttpClientModule} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {API_URL} from '../env';
import {Org} from './org.model';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class OrgApiService {
//create private variable 'http' of type HttpClient
constructor(private http: HttpClient) {
}
private static _handleError(err: HttpErrorResponse | any) {
// return Observable.throw(err.message || 'Error: Unable to complete request.');
return throwError(err.message || 'Error: Unable to complete request.');
}
getOrg(): Observable<Org[]> {
return this.http    
.get<Org[]>(`${API_URL}/org`)
.pipe(catchError(OrgApiService._handleError));
}
}

org.component.ts

import {Component, OnDestroy, OnInit} from '@angular/core';
import {Subscription} from 'rxjs/Subscription';
import {Org} from './org.model';
import {OrgApiService} from './org-api.service';
@Component({
selector: 'org',
template: `
<div>
<ul>
<li *ngFor="let org of orgList">
{{org.name}}
</li>
</ul>
</div>
`,
styleUrls: ['org.component.css'],
})
export class OrgComponent implements OnInit, OnDestroy {
orgListSubs: Subscription;
orgList: Org[];
authenticated = false;
constructor(private orgApi: OrgApiService) { }
ngOnInit() {
this.orgListSubs = this.orgApi
.getOrg()
.subscribe(res => {
this.orgList = res;
},
console.error
);
const self = this;
}
ngOnDestroy() {
this.orgListSubs.unsubscribe();
}
}

此外,我遇到了以下解决方案,并决定采用它,因为为什么不。。。无效:在我的前端目录中创建一个proxy.conf.json,其中包含以下内容

{
"/": {
"target": "http://0.0.0.0:5000",
"secure": false,
"logLevel": "debug"
}
}

然后将CCD_ 10选项添加到CCD_。

更新

@sideshowbarker指出,在某些情况下,302响应没有"Access Control Allow Origin"标头,在我的情况下,这是真的。在进一步挖掘后,我看到了这篇帖子,其中提到chrome在收到状态代码302后取消了请求。这也让我chrome://net-export/我发现我的请求也被取消了。

对于这个问题,我还没有一个明显的/可接受的解决方案。如果你正在阅读这篇文章并有建议。。请分享。

t=131761 [st=  4]      QUIC_CONNECTION_MIGRATION_MODE
--> connection_migration_mode = 0
t=131761 [st=  4]     +HTTP_TRANSACTION_SEND_REQUEST  [dt=0]
t=131761 [st=  4]        HTTP_TRANSACTION_QUIC_SEND_REQUEST_HEADERS
--> :method: GET
:authority: 5000-dot-XXXXXXX-dot-devshell.appspot.com
:scheme: https
:path: /
accept: application/json, text/plain, */*
sec-fetch-dest: empty
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
origin: https://4200-dot-XXXXXXX-dot-devshell.appspot.com
sec-fetch-site: cross-site
sec-fetch-mode: cors
referer: https://4200-dot-XXXXXXX-dot-devshell.appspot.com/?authuser=0&environment_name=default
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
--> quic_priority = 4
--> quic_stream_id = 5
t=131761 [st=  4]     -HTTP_TRANSACTION_SEND_REQUEST
t=131761 [st=  4]     +HTTP_TRANSACTION_READ_HEADERS  [dt=168]
t=131928 [st=171]        HTTP_TRANSACTION_READ_RESPONSE_HEADERS
--> HTTP/1.1 302
status: 302
date: Wed, 01 Apr 2020 06:33:46 GMT
content-type: text/html; charset=utf-8
content-length: 498
location: https://some.url.com
via: 1.1 google
alt-svc: quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,h3-T050=":443"; ma=2592000
t=131929 [st=172]     -HTTP_TRANSACTION_READ_HEADERS
t=131929 [st=172]      HTTP_CACHE_WRITE_INFO  [dt=0]
t=131929 [st=172]      HTTP_CACHE_WRITE_DATA  [dt=0]
t=131929 [st=172]      HTTP_CACHE_WRITE_INFO  [dt=0]
t=131929 [st=172]      NETWORK_DELEGATE_HEADERS_RECEIVED  [dt=1]
t=131930 [st=173]      URL_REQUEST_DELEGATE_RECEIVED_REDIRECT  [dt=0]
t=131930 [st=173]      CANCELLED
t=131930 [st=173] -REQUEST_ALIVE

我花了好几天的时间试图解决这个问题,但基本上没有成功。我觉得似乎有一个比我尝试过的一切都更简单的解决方案。提前感谢您的帮助!

已解决!

将前端/应用程序中的env.ts编辑为

export const API_URL = 'http://localhost:4200'

而不是localhost:5000

API_URL对应于ng服务开发部署

相关内容

  • 没有找到相关文章

最新更新