You need to enable JavaScript to run this app. Node.js开发BMI计算器出现Cannot read property 'weight' of undefined错误
优惠活动
大模型
产品
解决方案
定价
更多

Node.js开发BMI计算器出现Cannot read property 'weight' of undefined错误

核心问题定位
  • 报错Cannot read property 'weight' of undefined的直接原因是,代码里req.body本身就是undefined,自然不存在读取weight属性的可能。
  • 这个问题是body-parser中间件的挂载方式完全写错导致的:你现在写的app.get(bodyParser.urlencoded({extended: true}));存在两处核心错误:
    1. 全局请求解析中间件必须用app.use()挂载,而不是绑定到app.get()的路由方法上,这行代码根本没有把body解析逻辑注入到请求处理流程里
    2. 你传入的参数顺序完全反了,app.get()的第一个参数本该是请求路径,结果你直接把中间件函数当成了路径字符串,完全起不到路由匹配的作用。
修复操作
  1. 把之前写错的那行app.get(bodyParser.urlencoded({extended: true}));删除,替换为正确的中间件挂载代码,必须放在所有路由定义之前:
    app.use(bodyParser.urlencoded({ extended: true }));
    这行代码的作用是:所有经过服务的请求,只要是表单格式提交的参数,都会被自动解析成对象挂到req.body上,供后续路由逻辑读取。
  2. 替换后可正常运行的核心代码参考:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();

// 正确挂载表单解析中间件
app.use(bodyParser.urlencoded({extended: true}));

app.get("/bmicalculator",function(req, res){
    res.sendFile(__dirname+"/bmiCalculator.html");
});

app.post("/bmicalculator", function(req, res){
    var weight = parseFloat(req.body.weight);
    var height = parseFloat(req.body.height);
    var bmi = weight / (height * height);
    res.send("Your BMI is " + bmi);
});

app.listen(1990, function(){
    console.log("calc server started!!!");
});
  1. 额外前端侧检查:确认bmiCalculator.html里的表单配置符合后端读取逻辑——表单method设为POST、action指向/bmicalculator,两个输入框的name属性严格写为weight和height,字段名和后端读取的一致即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.28 06:54:03