I am learning express.js and I have this basic express code here:
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 inciude above
let n2 = req.body.num2
let result = n1 + n2
res.send(result)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
But it take n1 and n2 as strings. So if I give n1 = 2 and n2 = 4 it returns 24 but not 6 so I tried to convert n1 and n2 as numbers so I have tried
let n1 = Number(req.body.num1)
let n2 = Number(req.body.num2)
But it gives error called :
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 ServerResponse.send (C:\Users\USERNAME \OneDrive\Desktop\lll\calculator\node_modules\express\lib\response.js:232:10)
at ServerResponse.sendStatus (C:\Users\USERNAME \OneDrive\Desktop\\calculator\node_modules\express\lib\response.js:375:15)
at C:\Users\USERNAME \OneDrive\Desktop\lll\calculator\calculator.js:18:9
at Layer.handle [as handle_request] (C:\Users\USERNAME \OneDrive\Desktop\lll\calculator\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\USERNAME \OneDrive\Desktop\lll\calculator\node_modules\express\lib\router\route.js:144:13)
Even if I tried to console log the type of result
it returns this type of error. Can someone help me please
The index.html code :
<!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>Caluculator</title>
</head>
<body>
<h1>Caluculator</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>