2

I am very new in node Js and I am creating one simple calculator using express . while post call it's not going into the switch case method and not doing the math operation and giving default result. This is my calc.html under public

  <html>
    <head>
  <title> Login Page </title>
  </head>
    <body bgcolor="orange">
 <div align="center">
Welcome To Calcualtor Page <br/><br/>
<form action="calculate" method="post" target="result">
 Enter number a: <input type="text" name="a"> <br>
 Enter number b: <input type="text" name="b"> <br/>

   <input type="submit"  name="action" value="Add">
   <input type="submit"  name="action" value="Sub">
   </form>
   <hr/>
    <iframe  name="result" src="" width="200" height="200">
    </iframe>
    </div>
    </body>
    </html>

and this is app.js

             var express = require('express');
             var bodyParser = require('body-parser');
              var calc = require('./routes/calculate');
              var app = express();
               app.use(bodyParser.json());
               app.use(bodyParser.urlencoded({ extended: false }));
               app.use(express.static("public"));
               app.use('/calculate', calc);
               module.exports = app;

And this is calculate.js under routes

                   var express = require('express');
                    var router = express.Router();
                   router.post('/', function(request, response, next) {
                    var a=request.body.a;
              var b=request.body.b;
            var c= a+b;
             switch(request.params.operation) {
              case 'Add':
                 var answer = a + b;
                response.send(answer);
                break;
               case 'Sub':
                 var answer = a - b;
                 response.send(answer);
                break;
                     default:
                 response.send("default");
                }
                  });

                  module.exports = router;
  • If you write `console.log('params:', request.params);` just before the `switch`, what output do you get in the server log? – David Knipe May 05 '18 at 20:27
  • I cant see calculate/:operation! – ŞükSefHam May 05 '18 at 21:27
  • @DavidKnipe in the server log getting blank params:{} – Devendra Vastrakar May 06 '18 at 04:39
  • You've used `request.body` for `a` and `b`, but `request.params` for `operation`. I'm guessing `request.params` is for what's in the URL, e.g. `http://www.example.com?action=Add&a=7&b=4`. You're using the body, so try `request.body.operation` instead. And is it `operation` or `action`? Because the HTML code says `action`. Also, forms aren't meant to have 2 submit buttons that do different things. In this case I'd expect that both `` elements try to set the value of `action`, one of them gets ignored, and it doesn't care which one is actually pressed. – David Knipe May 06 '18 at 11:49

0 Answers0