Flask / Flask-CORS:缺少CORS标头“ Access-Control-Allow-Origin”

时间:2019-09-02 21:11:11

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

我正在尝试将在端口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()

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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'
    ]