【问题标题】:Flask/Flask-CORS: CORS header ‘Access-Control-Allow-Origin’ missingFlask/Flask-CORS:缺少 CORS 标头“Access-Control-Allow-Origin”
【发布时间】:2020-01-05 19:57:04
【问题描述】:

我正在尝试将在端口 5000 上本地运行的 Flask backend 与在端口 8080 上本地运行的 Vue.js frontend 链接。

我能够成功注册和登录,但无法在应用中提交文章,在浏览器控制台中出现以下错误。

跨域请求被阻止:同源策略不允许读取位于http://localhost:5000/api/articles 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。

Flask 后端使用 Flask CORS(为每个蓝图初始化它们),并且我已将 localhost/127.0.0.1 来源提供给白名单。

#settings.py
    CORS_ORIGIN_WHITELIST = [
        'http://0.0.0.0:4100',
        'http://localhost:4100',
        'http://0.0.0.0:8000',
        'http://localhost:8000',
        'http://0.0.0.0:4200',
        'http://localhost:4200',
        'http://0.0.0.0:4000',
        'http://localhost:4000',
        'http://localhost:8080',
        'http://0.0.0.0:8080',
        'http://127.0.0.1:8080',
        'http://192.168.100.6:8080',
        'localhost'
    ]

#app.py
def register_blueprints(app):
    """Register Flask blueprints."""
    origins = app.config.get('CORS_ORIGIN_WHITELIST', '*')
    cors.init_app(user.views.blueprint, origins=origins)
    cors.init_app(profile.views.blueprint, origins=origins)
    cors.init_app(articles.views.blueprint, origins=origins)

    app.register_blueprint(user.views.blueprint)
    app.register_blueprint(profile.views.blueprint)
    app.register_blueprint(articles.views.blueprint)

#extensions.py

cors = CORS()

任何帮助将不胜感激。

【问题讨论】:

    标签: python vue.js flask cors flask-cors


    【解决方案1】:

    您是否尝试将端口添加到 localhost 条目?

    #settings.py
        CORS_ORIGIN_WHITELIST = [
            'http://0.0.0.0:4100',
            'http://localhost:4100',
            'http://0.0.0.0:8000',
            'http://localhost:8000',
            'http://0.0.0.0:4200',
            'http://localhost:4200',
            'http://0.0.0.0:4000',
            'http://localhost:4000',
            'http://localhost:8080',
            'http://0.0.0.0:8080',
            'http://127.0.0.1:8080',
            'http://192.168.100.6:8080',
            'localhost:8080'
        ]
    

    【讨论】:

    • 我试过了,但没有结果,同样的错误:> 跨域请求被阻止:同源策略不允许读取localhost:5000/api/articles 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
    • 您的错误是标题完全丢失,这有点奇怪。列出了其他错误,如果您有错误的来源,我认为错误将类似于:“访问策略不允许”。可能是您的 Flask 应用配置错误,根本没有发送标头。
    猜你喜欢
    • 2018-03-28
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2021-12-07
    • 2023-03-21
    • 2020-11-12
    相关资源
    最近更新 更多