0

While I try to change the string value to number I am facing a error.

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(req,res){
    var num1=Number(req.body.num1);
    var num2=Number(req.body.num2);
    var result=num1+num2;
    res.send(result);
})
app.listen(3000,function(){
    console.log("server started");
})

When I am using the Number() function this error is raised. Can anybody help me with this?

I want the result to be shown in the localhost page

cafce25
  • 15,907
  • 4
  • 25
  • 31

2 Answers2

1

Using Response#send with a number will send that number as the response status code. You have to convert it to a string:

app.post("/",function(req,res){
    var num1=Number(req.body.num1);
    var num2=Number(req.body.num2);
    var result=num1+num2;
    res.send(result.toString());
})

The documentation states that:

The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.

grimsteel
  • 796
  • 1
  • 17
1

First, you'll probably want to include a line like app.use(bodyParser.json()) to make accessing data from your request body easier. For example:

//...
app.use(bodyParser.urlencoded({extended:true}));

app.use(bodyParser.json()) // add this line

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

The next issue is in your res.send() function. According to express documentation on this function:

res.send([body]) - Sends the HTTP response.

The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.

You're sending a number, which isn't supported so weird behavior is occuring. If you change it to a string or an object you should be fine. For example:

//...
  var result=num1+num2;
  res.send({ request });
//...

will result in a response like this (if the request gives 1 as num1 and 2 as num2):

{
    "result": 8
}

I hope that helps!

chill389cc
  • 365
  • 1
  • 10