0

I am unable to get cors enabled on my app inside my flask app using the flask_cors package after I started using blueprints in my app. I have the following structure

app
  api
     __init__.py
     api.py
  main.py

my init.py looks like the following

from flask import Blueprint
from flask_cors import CORS

api = Blueprint('api', __name__, url_prefix="/api")
cors = CORS()
cors.init_app(api, resources={r"/*": {"origins": "*", "supports_credentials": True}})

and my main.py

def setup_app_config(app):
    database_uri = 'postgresql+psycopg2://{user}:{password}@{host}/{database}?sslmode={sslmode}'.format(
            user=os.getenv('PGUSER'),
            password=os.getenv("PGPASSWORD"), 
            host=os.getenv("PGHOST"), 
            port=os.getenv("PGPORT"), 
            database=os.getenv("PGDATABASE"),
            sslmode=os.getenv("PG_SSL")
        )
    
    app.config.update(
        SQLALCHEMY_DATABASE_URI=database_uri,
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
    )
    CORS(app, resources={r"/api/*": {"origins": "*"}},  supports_credentials=True)

app = Flask(__name__)

setup_app_config(app)
db.init_app(app)

app.register_blueprint(api, urlprefix="/")

I keep getting the following error on browser console.

Access to XMLHttpRequest at 'http://localhost:8000/api/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
xhr.js?b50d:160 POST http://localhost:8000/api/login net::ERR_FAILED

On my axios config I am using the following flags withCredentials: true. Any tips on solving this would be greatly appreciated.

Bazinga777
  • 5,140
  • 13
  • 53
  • 92
  • a couple of links that might help you - https://flask-cors.readthedocs.io/en/v1.7.4/ .. https://stackoverflow.com/questions/61955973/issue-with-flask-cors-blocked-by-cors-policy-response-to-preflight-request-do – KcH Sep 24 '20 at 06:52

1 Answers1

1

Try removing all cors-related code from __init__.py, only leave CORS initialization in your setup_app_config

GProst
  • 9,229
  • 3
  • 25
  • 47