Flask服务/predict端点POST请求返回405 Method Not Allowed错误排查
Flask POST请求405错误及前端JSON解析失败解决方法
问题分析
后端配置了/predict POST端点,但前端请求返回405(方法不允许),同时前端出现JSON解析错误,已确认地址和CORS配置无误。
修复方案
1. 修正前端请求路径(相对路径指向错误服务器)
若前端与Flask后端运行在不同端口/域名下,相对路径/predict会请求前端服务器而非Flask后端。需替换为后端完整URL:
fetch("http://localhost:5000/predict", { // 替换为你的Flask服务实际地址 method: "POST", body: JSON.stringify({ message: text1 }), mode: "cors", headers: { "Content-Type": "application/json", }, }) // 后续代码保持不变
2. 统一前后端路径的斜杠匹配
若前端请求路径带末尾斜杠(/predict/),后端路由为/predict(无斜杠),Flask会自动重定向并将POST转为GET,触发405错误。解决方式二选一:
- 后端修改路由:
@app.post("/predict/") # 添加末尾斜杠 def predict(): # 原有代码不变 - 前端修改请求路径:去掉末尾斜杠,使用
"/predict"
3. 兼容旧版Flask的路由写法
若Flask版本低于2.0,@app.post装饰器不生效,需改用@app.route指定请求方法:
@app.route("/predict", methods=["POST"]) def predict(): text = request.get_json().get("message") print("Received message:", text) response = get_response(text) message = {"answer": response} return jsonify(message)
4. 添加后端JSON解析错误兜底
为避免因请求数据不合法导致前端JSON解析失败,在后端添加异常处理:
@app.route("/predict", methods=["POST"]) def predict(): try: data = request.get_json() if not data or "message" not in data: return jsonify({"error": "请求数据格式错误"}), 400 text = data.get("message") print("Received message:", text) response = get_response(text) return jsonify({"answer": response}) except Exception as e: print("服务器错误:", str(e)) return jsonify({"error": "服务器内部错误"}), 500
内容的提问来源于stack exchange,提问作者Daniel Ochoa
相关产品推荐
相关产品推荐

