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

Flask出现“Bad request”错误,无法获取JavaScript键值对如何解决?

解决Flask无法获取JavaScript传递数据导致的Bad Request错误

看起来你的问题核心在于JavaScript没有正确构造并发送请求数据,同时Flask后端也缺少必要的请求配置和错误处理,才会触发Bad Request。下面一步步帮你修复:

首先看JavaScript代码的问题

你的ledStudy函数只是定义了变量,但既没有正确构造要传递的数据,也没有把数据发送给Flask路由。而且变量声明的语法是错误的(var checkStudy.study是无效写法)。

修复后的JavaScript代码

function ledStudy() {
    var checkStudy = document.getElementById("checkStudy");
    // 构造要发送的键值对数据
    var requestData = {
        study: checkStudy.checked ? "on" : "off"
    };

    // 使用fetch API发送POST请求到Flask的路由
    fetch('/led-study', {
        method: 'POST',
        // 设置请求头,匹配表单数据格式,让Flask能解析
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        // 把对象转换为Flask能识别的表单格式
        body: new URLSearchParams(requestData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('请求失败');
        }
        return response.text();
    })
    .then(result => {
        console.log('操作成功:', result);
    })
    .catch(error => {
        console.error('错误:', error);
    });
}

再看Flask代码的问题

你的后端代码有两个关键问题:

  1. 没有指定路由接受POST请求(默认Flask路由只接受GET)
  2. 直接用request.form['study']会在参数不存在时抛出KeyError,进而触发Bad Request

修复后的Flask代码

from flask import Flask, request, render_template
import RPi.GPIO as GPIO

app = Flask(__name__)

# 初始化GPIO(建议放在路由外,避免重复初始化)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)

# 指定路由接受POST请求
@app.route('/led-study', methods=['POST'])
def ledStudy_handler():
    # 安全获取参数,避免KeyError
    study_state = request.form.get('study')

    if study_state == "on":
        GPIO.output(11, GPIO.HIGH)
        print("lights on")
    elif study_state == "off":
        GPIO.output(11, GPIO.LOW)
        print("lights off")
    else:
        # 处理无效参数的情况
        print("无效的状态参数")
        return "无效请求", 400

    return render_template("home.html")

# 主页路由(确保能访问到你的页面)
@app.route('/')
def home():
    return render_template("home.html")

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

额外注意点

确保你的HTML复选框正确绑定了ledStudy函数,比如:

<input type="checkbox" id="checkStudy" onclick="ledStudy()"> 书房灯控制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:56:39