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

Flask词典APP POST请求报KeyError:'word'问题求助

Flask词典应用POST请求KeyError('word')问题排查与修复

错误原因分析

终端报错KeyError:'word',本质是后端尝试从request.get_json()返回的对象中获取word键失败,由以下前端+后端问题共同导致:

  • 前端jQuery选择器错误:获取输入框值时未使用ID选择器前缀#,无法正确读取输入内容
  • 请求Content-Type格式错误:参数分隔符使用错误且存在多余空格,导致后端无法正确解析JSON
  • 表单提交未阻止默认行为:浏览器默认刷新页面,可能中断AJAX请求
  • 后端未做异常防护:直接访问字典键,未处理request.get_json()返回None的情况

修复代码

1. 前端JavaScript修复

$('#word-form').submit(function(e) {
    // 阻止表单默认提交行为,避免页面刷新
    e.preventDefault();
    
    // 使用ID选择器正确获取输入框值
    let word = $('#word').val();
    let meaning = $('#meaning').val();

    $.ajax({
        url: '/word',
        type: 'POST',
        dataType: 'json',
        data : JSON.stringify({
            'word': word,
            'meaning': meaning
        }),
        // 修正Content-Type格式,符合HTTP规范
        contentType: 'application/json; charset=UTF-8',
        success: function(data) {
            location.reload();
        },
        error: function(err) {
            console.log(err);
        }
    })
})

2. 后端Flask代码优化

@app.route('/word', methods= ['POST'])
def add_word():
    req = request.get_json()
    
    # 安全获取字段,避免KeyError
    word = req.get('word') if req else None
    meaning = req.get('meaning') if req else None
    
    # 校验必填字段
    if not word or not meaning:
        return json.dumps("error: missing word or meaning"), 400
        
    conn = mysql.get_db()
    cur = conn.cursor()
    try:
        cur.execute('insert into word(word, meaning) VALUES (%s, %s)',(word, meaning))
        conn.commit()
    finally:
        # 确保数据库资源被正确释放
        cur.close()
        conn.close()

    return json.dumps("success")

验证步骤

  1. 重启Flask应用,打开页面
  2. 在输入框填入单词和释义,点击提交
  3. 检查终端是否无KeyError,数据库是否新增对应记录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:15:56