I am learning express node.js and trying to run simple calculator code but anytime i press on the button i don't get any response back and also i don't get any errors in my code so i am kind of lost of what i am doin wrong. here is the sample of it so hoping someone can pinpoint me where i am goin wrong will include html code and calculator.js and the error which i am getting. Thank you in advance.
<!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>
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");
});
But here is the error i am getting as soon as i am clicking calculate button:
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)
CodePudding user response:
app.post("/",function(res,req){
You should change this to
app.post("/",function(req,res){
This worked for me!
CodePudding user response:
Are you providing req.body, when you're doing request? Looks like that is undefined!