CORS 策略阻止聊天机器人应用程序中的获取请求

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

我正在开发一个聊天机器人应用程序,使用 React 作为前端(在 localhost:3000 上运行),使用 Flask 作为后端 API(在 127.0.0.1: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.

每当我在聊天界面中输入内容时,就会弹出此错误,触发对后端 /predict 端点的获取请求。这是我的 React 应用程序中的获取请求代码:

fetch("http://127.0.0.1:5000/predict", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({ message: userInput })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

这是我的 Flask 后端的相关部分:

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()
    # Process the data
    response = {"reply": "Processed message"}
    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True)

我已经尝试使用flask_cors.CORS(app)在Flask中启用CORS,但问题仍然存在。我正在寻找有关如何正确配置 CORS 或任何其他可能解决此错误的设置的建议。

预先感谢您的帮助!

python flask cors bots chat
1个回答
0
投票

尝试在 Flask 设置中更改 CORS。

当我的团队为 Flask 创建 API 时,我们遇到了同样的问题,这个设置帮助了我们。

CORS(app, resources={r"/predict": {"origins": "http://localhost:3000"}})

您还可以尝试向 POST 请求添加新标头:

"Origin": "http://localhost:3000"
© www.soinside.com 2019 - 2024. All rights reserved.