Flask CORS问题-未通过OPTION请求

时间:2019-03-02 09:45:41

标签: flask flask-cors

我花了三天时间修复此CORS错误,但失败了。 您能指导我如何解决这个问题吗?

我在具有Docker容器的同一台本地计算机中配置了Angular(前端)+ Flask(后端api)。 (Ubuntu 16.04)

Docker#1 :暴露端口5000的烧瓶。   ->使用manage.py --host 0.0.0.0进行外部访问。

Docker#2 :暴露了端口4200的角度应用程序。   ->使用ng serve --port 0.0.0.0进行外部访问。

curl --user username:password http://127.0.0.1:5000/v1/classes/在我的主机PC和有角度的docker容器中成功完成。 在chrome浏览器中,也可以浏览网址。

但是当我尝试在角度代码中调用get api时,遇到了OPTION的CORS错误;

OPTIONS http://127.0.0.1:5000/v1/classes/ 401 (UNAUTHORIZED)
Access to XMLHttpRequest at 'http://127.0.0.1:5000/v1/classes/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

这是我的角度服务代码;

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { delay, map, catchError, tap } from 'rxjs/operators';

const endpoint = 'http://127.0.0.1:5000/v1/';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic ' + btoa('username:password')
  })
};

@Injectable()
export class ExampleCRUDService {

  constructor(private http: HttpClient) {}

  private extractData(res: Response) {
    let body = res;
    return body || { };
  }

  getClasses(): Observable<any> {
    return this.http.get(endpoint + 'classes/', httpOptions).pipe(
      map(this.extractData));
  }
}

测试 以下是我从烧瓶方面进行的试验,但没有一个成功。

CORS(app)
@app.route("/")
@cross_origin()
CORS(app, resources={r"/*": {"origins": "*"}})
@app.after_request
def after_request(response):
   response.headers.add('Access-Control-Allow-Origin', '*')
   response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
   response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
   return response
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resources={r"/v1": {"origins": "http://localhost:4200"}})

@app.route('/')
@cross_origin(origin='localhost',headers=['Content-Type','Authorization'])

CORS(app, expose_headers='Authorization')

1 个答案:

答案 0 :(得分:1)

即使使用以下方法,您也面临CORS问题,我感到很惊讶:

CORS(app)

只需尝试以下:

CORS(app, origins=['127.0.0.1:4200'])

我希望这能解决您的问题。让我知道您是否仍然遇到问题。