Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

364
Visualizações
Can't run any normal javascript code in node.js express.js

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>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda