从 React 应用程序向 Flask 服务器发出 POST 请求时出现 CORS 策略错误

问题描述 投票:0回答:1

我使用 Flask 后端和 React 前端开发了一个聊天机器人。当我尝试将数据从 React 应用程序(在 localhost:3000 上运行)发送到 Flask 后端(在 localhost:5000 上运行)时,遇到 CORS 策略错误。错误信息是:

Access to fetch at 'http://127.0.0.1:5000/predict' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

这是我的 Flask 应用程序(app.py)的相关部分:

from flask import Flask, render_template, request, jsonify
import logging
from flask_cors import CORS  # Ensure flask_cors is installed and imported

from chat import get_response  # Assuming 'chat' is a custom module you've defined

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)

# Enable CORS only for the /predict route from a specific origin
CORS(app, resources={r"/predict": {"origins": "http://localhost:3000"}})

@app.route("/", methods=['GET'])
def index_get():
    return render_template("base.html")

@app.route("/predict", methods=['POST'])
def predict():
    try:
        data = request.get_json()
        text = data.get("message")
        if not text:
            app.logger.error("No message provided")
            return jsonify({"error": "No message provided"}), 400
        response = get_response(text)
        app.logger.info(f"Received response: {response}")
        return jsonify({"answer": response})
    except Exception as e:
        app.logger.error(f"An error occurred: {e}")
        return jsonify({"error": "An error occurred processing your request"}), 500

if __name__ == "__main__":
    app.run(debug=False, port=5000)

我怀疑该问题可能与 /predict 路由的 CORS 设置方式有关,或者可能与预检请求由于某种原因失败有关。谁能帮助我了解我可能做错了什么或建议进行任何更改来解决此问题?

提前谢谢您!

python reactjs flask cors
1个回答
0
投票

您已将 CORS 设置为允许请求

http://localhost:3000
。这意味着如果您向任何其他路由发出请求,它们将被浏览器的 CORS 策略阻止。

如果您想允许 from

http://localhost:3000
到所有路线的请求,请将您的 CORS 更改为:

CORS(app, origins="http://localhost:3000")

如果您想允许请求从所有出发地到所有路线,请将您的 CORST 更改为:

CORS(app)

如果您仍然遇到问题,可能是服务器的问题 😬。

© www.soinside.com 2019 - 2024. All rights reserved.