【问题标题】:Why React can't reach Flask endpoints in production?为什么 React 无法在生产环境中访问 Flask 端点?
【发布时间】:2021-06-08 12:39:51
【问题描述】:

我在生产后端有一个带有 Flask 的 React 应用程序,我发现 我的任何端点都无法从 React 到达。

我知道在使用客户端路由时,开发人员需要使用包罗万象的功能 类似于下面:

@app.errorhandler(404)
def error_handler(e):
    return render_template('index.html')

我正在使用 Flask-CORS 来处理跨源请求:

在 config.py 中:

class ProductionConfig:
    CORS_HEADERS = 'Content-Type'
    ...
    ...

我的蓝图:

CORS(auth_blueprint, resources={r'/*': {"origins": "https://example.com", "allow_headers": "*", "expose_headers": "*"}})

@auth_blueprint.route('/auth/login', methods=['POST'])
@cross_origin()
def login():
    ...
    ...

在前端我定义这样的标题:

const headers = { "Access-Control-Allow-Origin": "*" };
const url = "https://example.com:5000/auth/login";
axios.post(url, data, headers).then(resp => { ... })

而且我没有收到任何错误。服务器的日志是干净的,控制台只显示Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com:5000/auth/login. (Reason: CORS request did not succeed)。 “原因:CORS 请求未成功”表示服务器没有返回任何内容。 该应用程序渲染良好,但 React (axios) 无法到达我的端点。有什么我不知道的陷阱吗?发送请求时,我什至没有在网络选项卡中获得状态代码。

谢谢。

网络标签的屏幕截图:

【问题讨论】:

    标签: reactjs flask axios flask-cors


    【解决方案1】:

    您需要将连接协议更改为http

    【讨论】:

    • 没关系。此外 https 是一个标准。
    • 不,有问题。特别是如果您在本地 PC 上工作,当然没有证书。 stackoverflow.com/questions/19541547/…
    • 抱歉,在这种情况下你是对的。我的生产服务器使用加密。
    • 你能提供你的浏览器开发者网络标签的截图吗?工具包?
    • 已添加屏幕截图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2014-05-21
    • 1970-01-01
    • 2020-12-28
    相关资源
    最近更新 更多