Dorr
Dorr

Reputation: 654

Flask CORS issue - OPTION request is not passed

I spend three days to fix this CORS error but failed. Could you please guide me how to solve this?

I configured Angular(frontend) + Flask(backend api) in the same local machine with docker containers. (Ubuntu 16.04)

Docker#1 : flask with port 5000 exposed. -> Ran with manage.py --host 0.0.0.0 for external access.

Docker#2 : angular app with port 4200 exposed. -> Ran with ng serve --port 0.0.0.0 for external access.

The curl --user username:password http://127.0.0.1:5000/v1/classes/ succeeded in my host PC and inside angular docker container. Also navigate the url is OK in the chrome browser.

But I met CORS error for the OPTION when I tried to call get api in the angular code;

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.

Here's my angular service code;

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

TEST Below is my trials from flask side but non of it succeeded.

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')

Upvotes: 2

Views: 3641

Answers (1)

Harshad Kavathiya
Harshad Kavathiya

Reputation: 10314

I am surprised that you are facing CORS issue even if you use the following:

CORS(app)

Just try follwing:

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

I hope this will solve your issue. Let me know if you still face the issue.

Upvotes: 2

Related Questions