Currently, I'm in the process of learning express.js and I've come across this simple express code snippet:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: true }))
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html")
})
app.post("/", (req, res) => {
let n1 = req.body.num1 //num1 and num2 are coming from index.html which I have included above
let n2 = req.body.num2
let result = n1 + n2
res.send(result)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
However, it seems that the values for n1 and n2 are being treated as strings. So when I enter n1 = 2 and n2 = 4, instead of getting 6, I get 24. To address this issue, I tried converting n1 and n2 to numbers like so:
let n1 = Number(req.body.num1)
let n2 = Number(req.body.num2)
But this resulted in an error:
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 5
at new NodeError (node:internal/errors:372:5)
at ServerResponse.writeHead (node:_http_server:275:11)
at ServerResponse._implicitHeader (node:_http_server:266:8)
at write_ (node:_http_outgoing:766:9)
at ServerResponse.end (node:_http_outgoing:855:5)
at...
Even when I attempted to log the type of result
, I encountered another error. Can anyone offer some assistance with this problem?
The code for index.html is as follows:
<!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>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form action="/" method="post">
<input type="text" name="num1" placeholder="Enter First Number" />
<input type="text" name="num2" placeholder="Enter Second Number" />
<button type="submit" name="submit">Calculate</button>
</form>
</body>
</html>