Express Node.js计算器点击Calculate按钮报错:TypeError无法读取n1属性
问题定位与解决:Express计算器无响应且报错
问题描述
学习Express Node.js时,运行简易计算器代码,点击Calculate按钮后无响应,随后出现报错:TypeError: Cannot read properties of undefined (reading 'n1')
相关代码
HTML代码
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>Calculator</h1> <form action="/" method="post"> <input type="text" name="n1" placeholder="Enter Number1" value=""> <input type="text" name="n2" placeholder="Enter Number2" value=""> <button type="submit" name="submit">Calculate</button> </form> </body> </html>
calculator.js代码
const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({extended : true})); app.get("/",function(req,res){ res.sendFile(__dirname +"/index.html"); }); app.post("/",function(res,req){ var n1 = Number(req.body.n1); var n2= Number(req.body.n2); var result= n1 + n2; res.send("The result of calculation is" + result); }); app.listen(2424,function(){ console.log("Server started on 2424"); });
报错信息
TypeError: Cannot read properties of undefined (reading 'n1') at C:\Users\Taniya\desktop\calculator\calc.js:12:28 at Layer.handle [as handle_request] (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\layer.js:95:5) at C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\index.js:284:15 at Function.process_params (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\index.js:280:10) at C:\Users\Taniya\desktop\calculator\node_modules\body-parser\lib\read.js:137:5 at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
问题原因与解决方法
核心问题是post请求处理函数的参数顺序写反了:
Express路由处理函数的参数固定顺序是(req, res)——先接收请求对象req,再接收响应对象res。你把两者位置写反后,代码里的req实际是响应对象,自然不存在req.body属性,因此触发“无法读取undefined的n1属性”报错。
修改后的post处理代码:
app.post("/",function(req, res){ var n1 = Number(req.body.n1); var n2= Number(req.body.n2); var result= n1 + n2; res.send("The result of calculation is " + result); });
额外优化建议:
- 给结果字符串添加空格,让显示更美观:
"The result of calculation is " + result - 可增加输入合法性判断,比如校验输入是否为有效数字,避免非数字输入导致计算异常。
内容的提问来源于stack exchange,提问作者Astha Raj
相关产品推荐
相关产品推荐

