【问题标题】:Flask CORS sometimes work and sometimes doesn'tFlask CORS 有时有效,有时无效
【发布时间】:2021-09-07 20:17:24
【问题描述】:

我在 tornado WSGI 容器中部署了一个烧瓶应用程序。龙卷风服务器托管在http://localhost:5000。整个事情都是使用 Nginx 反向代理部署的。烧瓶通过 CORS 将其端点提供给 tornado 服务器:

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = ['Content-Type', 'Authorization']
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

flask应用的部署方式如下:

flask_app = tornado.wsgi.WSGIContainer(app)
tornado_app = tornado.web.Application(
    [   
        # tornado specific handlers,
        (r"/(.*)", tornado.web.FallbackHandler, dict(fallback=flask_app))
    ], 
    log_function=log_function,                                      
    websocket_max_message_size=100 * 1024 * 1024)
http_server = tornado.httpserver.HTTPServer(
    tornado_app,
    max_buffer_size=1024 ** 3,
)

这是我的 Nginx 配置:

upstream frontend {
    server localhost:5000;
}

gzip on;
gzip_types text/plain text/css text/xml
           application/x-javascript application/xml
           text/javascript;

proxy_next_upstream error;

server {
    listen <server_ip>:80;
    server_name <server_hostname>;

    auth_basic "Administrator's Area";
    auth_basic_user_file /etc/nginx/.htpasswd;

    location / {
        proxy_pass http://frontend/;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;
        proxy_set_header X-Scheme $scheme;
    }
}

当我使用 Nginx 反向代理时,我收到所有烧瓶端点的 CORS: Request did not succeed 错误。没有它,localhost:5000 的龙卷风服务器将接受所有烧瓶路由。有时,它会自行工作,有时则不会。大多数情况下,是后者。我也尝试在 Nginx 配置中设置特定于 cors 的标头,但它不起作用。

【问题讨论】:

    标签: python-3.x nginx flask tornado flask-cors


    【解决方案1】:

    花了很多时间来解决这个问题,但我很高兴提出解决方案(以防有人找到)。实际上,我不再需要使用flask-CORS。在部署中,来源始终相同,即&lt;server_hostname&gt;&lt;server_ip&gt;。解决步骤:

    1. 删除了烧瓶应用程序中的 cors 和配置行
    2. 在我的 tornado 应用程序中,我像这样替换了烧瓶路线:
    http://localhost:5000/flask_app
    # to
    http://<server_hostname>/flask_app
    
    1. 如果您在 Nginx 中配置了 cors,请同时删除相应的 add_header 指令。

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 2013-07-06
      • 2015-02-11
      • 2012-08-02
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多