【问题标题】:Unable to run cors on flask app with blueprints无法在带有蓝图的烧瓶应用程序上运行 cors
【发布时间】:2021-01-10 08:47:34
【问题描述】:

在我开始在我的应用程序中使用蓝图后,我无法使用 flask_cors 包在我的烧瓶应用程序内的应用程序上启用 cors。我有以下结构

app
  api
     __init__.py
     api.py
  main.py

我的 init.py 如下所示

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

还有我的 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="/")

我在浏览器控制台上不断收到以下错误。

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

在我的 axios 配置中,我使用了以下标志 withCredentials: true。任何解决此问题的提示将不胜感激。

【问题讨论】:

标签: python flask cors


【解决方案1】:

尝试从__init__.py 中删除所有与cors 相关的代码,只在setup_app_config 中保留CORS 初始化

【讨论】:

  • 嗨,很抱歉回复晚了,但这实际上是我所做的并且得到了它的工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 2020-04-16
  • 2020-12-22
  • 2017-12-25
  • 2013-04-07
  • 1970-01-01
相关资源
最近更新 更多