Flask服务器访问出现404 Not Found问题求助
解决Flask服务器根路径404问题
你遇到的404错误原因很明确:浏览器访问http://localhost:5000/时发送的是GET请求,但你的根路由@app.route('/', methods=['POST'])只配置了接受POST请求,服务器找不到对应GET请求的处理逻辑,所以返回Not Found。
解决方案1:给根路由添加GET请求支持(适合测试)
修改路由装饰器,把GET加入允许的请求方法列表,同时添加GET请求的响应逻辑,比如返回接口使用说明:
@app.route('/', methods=['POST', 'GET']) def do_classification(): if request.method == 'GET': # 处理GET请求,返回接口使用提示 return jsonify({'message': '请使用POST请求,传入JSON格式的{"input": "你的输入内容"}'}) # 保留原有的POST请求处理逻辑 try: data = request.get_json() user_input = data['input'] prediction = classify(user_input) print(f'Received input "{user_input}" from chat server') print(f'Classified input as: "{prediction}" from chat server') response = jsonify({'prediction': prediction}) return response except Exception as e: return jsonify({'error': str(e)})
注:你已经通过CORS(app, resources={r"/*": {"origins": "*"}})配置了全局CORS,后面response.headers.add('Access-Control-Allow-Origin', '*')属于重复配置,可以删除。
解决方案2:用POST请求工具测试接口(适合正式场景)
如果这个接口本来就只应接受POST请求,不要用浏览器直接访问,改用以下方式测试:
- 使用
curl命令:
curl -X POST -H "Content-Type: application/json" -d '{"input": "测试内容"}' http://localhost:5000/
- 用Postman、Insomnia这类API测试工具,发送POST请求,设置请求体为JSON格式,传入
{"input": "你的输入内容"}
内容的提问来源于stack exchange,提问作者goth gamer gal
相关产品推荐
相关产品推荐

