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

Node.js提交表单到RestAPI插入MySQL无法获取参数报错如何解决

解决方案

你需要依次修改以下几处问题:

1. 修正前端表单配置

表单提交依赖name属性识别字段,你之前使用自定义属性导致表单无法正常提交参数,修改为:

<form action="/add_people" method="post">
    <h1>请输入名</h1>
    <input type = "text" name="firstname">
    <h1>请输入姓</h1>
    <input type = "text" name="lastname">
    <input type="submit" class="btn btn-primary">
</form>

2. 修正Node.js服务端配置

  • 首先安装body-parser依赖,用于解析POST请求体:npm install body-parser
  • 引入中间件并修改路由逻辑,把表单参数传递给Python RestAPI:
// 项目入口开头先引入并配置body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 修改路由逻辑
app.post('/add_people', async function(req, res){
    try {
        // 从表单请求中获取两个字段
        const { firstname, lastname } = req.body;
        // 发POST请求带参数到Python API
        const response = await axios.post('http://127.0.0.1:5000/api/adduser', {
            firstname,
            lastname
        }, {
            headers: { 'Content-Type': 'application/json' }
        });
        console.log(response.data);
        // 跳转到感谢页
        res.redirect('/thanks');
    } catch (err) {
        console.error('请求出错', err);
        res.status(500).send('提交失败');
    }
});

3. 修正Python RestAPI配置

  • 增加空值判断,避免get_json()返回None时报错
  • 替换字符串拼接SQL为参数化查询,避免SQL注入风险
@app.route('/api/adduser', methods = ['POST'])
def adding_stuff():
    request_data = request.get_json()
    # 增加空值判断
    if not request_data or 'firstname' not in request_data or 'lastname' not in request_data:
        return '参数错误', 400
    new_fname = request_data['firstname']
    new_lname = request_data['lastname']
    conn = create_connection("", "", "", "")
    # 改为参数化查询
    sql = "INSERT INTO restaurantusers (firstname, lastname) VALUES (%s, %s);"
    execute_query(conn, sql, (new_fname, new_lname))
    return 'Post worked'

注意:如果你的execute_query方法不支持传参数元组,需要对应调整方法实现,不要直接拼接字符串到SQL语句中。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:45:04