0

I Have the following HTML Form:

<form class="" action="/" method="post">
      <input type="text" name="num1" placeholder="First Number">
      <input type="text" name="num2" placeholder="Second Number">
      <button type="submit" name="submit">Calculate</button>
    </form>

What I want to do is to get the two entered numbers and post their sum. In my express.js server, I included the body-parser package and when I write the following route:

  app.post("/", function(req,res) {

  var num1 = Number(req.body.num1);
  var num2 = Number(req.body.num2);

  res.send(num1+num2);

})

After pressing the submit button, I get the following error showing:

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 5

I also tried using the parseInt() function but it displayed the same error.

What does this error mean? And how can I fix it?

Ziv Aviv
  • 59
  • 1
  • 7
  • 2
    What do you receive for `req.body.num1` and `req.body.num2`? – VLAZ Oct 07 '20 at 09:29
  • its gives me the two inputs the user entered. The problem is that those values are strings, so I cant sum their app. Therefor, I needed to parse them to Integers. – Ziv Aviv Oct 07 '20 at 09:30
  • 2
    Also, your error doesn't seem at all connected to the use of `Number` - it claims that the *status code* is incorrect and it's `5`. This isn't a valid status code which is what the error you get is saying. Somewhere you're changing the status code of the response. – VLAZ Oct 07 '20 at 09:33
  • 1
    Are you sure you're not doing `res.status(num1+num2)`? That would make more sense considering the error message. – Ivan Oct 07 '20 at 09:34
  • when I remove the Number() and run the program, it gives me the incorrect answer. For example, if the two numbers the user entered are 3 and 5, it sends 35. This error only occurs when I include the Number() function. – Ziv Aviv Oct 07 '20 at 09:38
  • 1
    `res.send([body])` can't receive a Number as parameter: [see doc](http://expressjs.com/en/5x/api.html#res.send) – Ivan Oct 07 '20 at 09:42
  • 1
    express 4.x treats `res.send()` as `res.send(status, body)` ([source](https://github.com/expressjs/express/blob/dc538f6e810bd462c98ee7e6aae24c64d4b1da93/lib/response.js#L123)). This behavior got changed with 5.x ([Source](https://github.com/expressjs/express/blob/f4120a645301366891775d1f03925449239a2cb7/lib/response.js#L123)) – Andreas Oct 07 '20 at 09:48

2 Answers2

2

Try converting the return value to String.

res.send(String(num1 + num2));
IRSHAD
  • 1,582
  • 11
  • 16
2

According to the doc http://expressjs.com/en/api.html#res.send res.send expects Buffer object, a String, an object, Boolean, or an Array

Assuming you have body-parser configured you can use

res.send([num1 + num2]) to get the result

ihoryam
  • 1,941
  • 2
  • 21
  • 24