为什么我不断得到这个RangeError时做这个简单的数学计算节点?



所有我的程序真正做的是在HTML表单上接受两个输入,并将其解析为node中的文本,然后对这两个进行数学运算。奇怪的是,它只发生在打印数字时。

有趣的是,它仍然打印正确的数字,但它被标记为无效状态码。可以在错误的顶部看到。

下面是HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BMI Calculator</title>
</head>
<body>
<h1>BMI Calculator</h1>
<form action="/bmicalculator" method="post">
<input type="number" name="height" placeholder="Height">
<input type="number" name="weight" placeholder="Weight">
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
下面是js代码:
const express = require('express');
const bodyParser = require('body-parser');
const res = require('express/lib/response');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/bmicalculator', function(req, res) {
res.sendFile(__dirname + '/bmiCalculator.html');
});
app.post('/', function(req, res) {
let num1 = Number(req.body.num1);
let num2 = Number(req.body.num2);
let r = num1 + num2;
res.send(r);
})
app.post('/bmicalculator', function(req, res) {
let weight = Number(req.body.weight);
let height = Number(req.body.height);
let r = weight * height;
res.send(weight);
})
app.listen(3000, function() {
console.log('server started');
});

错误如下:

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 12
at new NodeError (node:internal/errors:371:5)
at ServerResponse.writeHead (node:_http_server:274:11)
at ServerResponse._implicitHeader (node:_http_server:265:8)
at ServerResponse.end (node:_http_outgoing:871:10)
at ServerResponse.send (/Users/user/Desktop/Calculator/node_modules/express/lib/response.js:221:10)
at /Users/user/Desktop/Calculator/calculator.js:28:9
at Layer.handle [as handle_request] (/Users/user/Desktop/Calculator/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/user/Desktop/Calculator/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/user/Desktop/Calculator/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/user/Desktop/Calculator/node_modules/express/lib/router/layer.js:95:5)

你应该这样做:

app.post('/', function(req, res) {
let num1 = Number(req.body.num1);
let num2 = Number(req.body.num2);
let r = num1 + num2;
res.send(`${r}`);
})
app.post('/bmicalculator', function(req, res) {
let weight = Number(req.body.weight);
let height = Number(req.body.height);
let r = weight * height;
res.send(`${weight}`);
})

最新更新