Home > database >  Can't run any normal javascript code in node.js express.js
Can't run any normal javascript code in node.js express.js

Time:05-20

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>

CodePudding user response:

The error come from this line res.sendStatus(result) Result is not a valid statut code. Instead of

let n1 = Number(req.body.num1);

Put

const n1 =  req.body.num1;
const n2 =  req.body.num2;
const result= n1 n2;
res.status(200).send({result, 
message:"success"});

The status code must be from 100 to 599

CodePudding user response:

I found the answer like this Unable to send numbers using res.send() using express with node

You must send string instead of number

app.post("/", (req, res) => {
    let n1 = Number(req.body.num1) //num1 and num2 are coming from index.html which I have inciude above
    let n2 = Number(req.body.num2)

    let result = n1   n2
    res.send('' result)
})

I tested and it run

CodePudding user response:

The answer is :

let n1 = req.body.num1
let n2 = req.body.num2
let result = Number(n1)   Number(n2)
res.send(""   result)

You have to just add an empty string. I don't know why it works but it worked

CodePudding user response:

The error does come from res.sendStatus(result) and should instead be res.send(result). If you do want to manually set the status, then it should be res.status(200).send(result), exchanging 200 for the status code you want to set.

On top of this, you should also convert the number to a string. The most performant way is debateable, but my usual method of doing so is like ${n1 n2}.

In your case, with the changes mentioned above, your JavScript should look like:

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}`)
})

There's some more information in the Express documentation.

CodePudding user response:

let n1 = parseInt(req.body.num1);  
let n2 = parseInt(req.body.num2);  
let result = n1   n2;  
return res.status(200).send({result});  

You will get an integer value after using parseInt().
also, you can use a sign before variable.

let num1 = "2";  
let num2 = "4";  
let n1 = parseInt(num1);  
let n2 = parseInt(num2);  
let result = n1   n2;  
console.log('result >>>', result);

  • Related