You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask与Fetch POST请求出现500错误,请求技术协助

解决Flask POST请求500错误的方案

核心问题

你的Flask视图函数get_input_text没有返回任何响应内容,Flask要求所有视图函数必须返回有效的HTTP响应(字符串、响应对象或符合格式的元组),否则服务器会抛出500内部错误。

修复步骤

  1. 修改Flask代码,为/post路由添加返回值:

    from flask import Flask, render_template, redirect, url_for, request, jsonify
    
    app = Flask(__name__)
    
    @app.route('/tasks/today')
    def homepage():
        return render_template('index.html', action='Мой день')
    
    @app.route('/')
    def redirect_to_homepage():
        return redirect('/tasks/today')
    
    @app.route('/post', methods=['GET', 'POST'])
    def get_input_text():
        print('Function worked!')
        # 处理POST请求,解析JSON并返回响应
        if request.method == 'POST':
            data = request.get_json()
            print(f"Received data: {data}")
            return jsonify({"status": "success", "data": data}), 200
        # GET请求返回基础提示
        return "This is a POST-only endpoint", 200
    
    app.run(debug=True)
    
    • 导入request和jsonify模块,用于解析请求数据和返回标准JSON响应
    • 为POST请求添加数据解析逻辑,同时返回成功状态码和响应内容
    • 开启debug=True,方便查看详细错误堆栈信息,快速定位问题
  2. 优化JS代码,添加响应处理逻辑便于调试:

    let user = {
        name: 'John',
        surname: 'Smith'
    };
    
    fetch('/post', {
        method: 'POST',
        headers: {'Content-Type': 'application/json;charset=utf-8'},
        body: JSON.stringify(user)
    })
    .then(response => {
        console.log('Response status:', response.status);
        return response.json();
    })
    .then(data => console.log('Response data:', data))
    .catch(error => console.error('Request error:', error));
    

内容的提问来源于stack exchange,提问作者TheSawe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 21:52:25