Unable to execute standard JavaScript code in node.js using express.js

Currently, I'm in the process of learning express.js and I've come across this simple express code snippet:

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 included above
    let n2 = req.body.num2

    let result = n1 + n2
    res.send(result)
})
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

However, it seems that the values for n1 and n2 are being treated as strings. So when I enter n1 = 2 and n2 = 4, instead of getting 6, I get 24. To address this issue, I tried converting n1 and n2 to numbers like so:

let n1 = Number(req.body.num1)
let n2 = Number(req.body.num2)

But this resulted in an error:

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...

Even when I attempted to log the type of result, I encountered another error. Can anyone offer some assistance with this problem?

The code for index.html is as follows:

<!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>Calculator</title>
</head>
<body>
    <h1>Calculator</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>

Answer №1

The issue arises from the following line res.sendStatus(result) The "result" variable does not contain a valid status code. Instead of

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

Use

const num1 = +req.body.num1;
const num2 = +req.body.num2;
const finalResult = num1 + num2;
res.status(200).send({finalResult, 
message: "Operation successful"});

Status codes should range from 100 to 599

Answer №2

I stumbled upon the solution by referencing this thread on Stack Overflow

The key is to send a string instead of a 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)
})

After testing it out, everything worked smoothly.

Answer №3

Here is the solution :

const firstNumber = req.body.num1;
const secondNumber = req.body.num2;
const sum = Number(firstNumber) + Number(secondNumber);
res.send(String(sum));

Simply appending an empty string seems to do the trick. It's a strange workaround, but it gets the job done.

Answer №4

The issue is stemming from the use of res.sendStatus(result), which should be changed to res.send(result). If you wish to specify the status code manually, you can do so by using res.status(200).send(result), replacing 200 with your desired status code.

Additionally, it's important to convert the number to a string. While there are various methods to achieve this, a commonly used approach is like ${n1 + n2}.

Following these adjustments, your JavaScript code would appear as follows:

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 
    let n2 = req.body.num2

    let result = n1 + n2
    res.send(`${result}`)
})
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

For further insights, refer to the Express documentation.

Answer №5

let firstNumber = parseInt(req.body.num1);  
let secondNumber = parseInt(req.body.num2);  
let result = firstNumber + secondNumber;  
return res.status(200).send({result});  

By using parseInt(), you will receive an integer value.
Additionally, you can apply a + sign before a variable.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for deactivating a button based on the list's size

I am trying to implement a feature where the user can select only one tag. Once the user has added a tag to the list, I want the button to be disabled. My approach was to disable the button if the length of the list is greater than 0, but it doesn't s ...

Having trouble: How can I show the value in a modal using jquery-ajax?

Struggling to pass a value to modal using jQuery/ajax. Still getting the hang of jQuery/ajax. The code: <script type="text/javascript> $(".Buto").on("click",function () { var dataID = $(this).data('id'); $.ajax({ ...

Sending data to Firebase Storage with AngularFire2

I've been working on a project involving Angular2 and Firebase, aiming to upload images to Firebase Storage. In order to achieve this, I created the Component with the constructor, function, and template. However, I am unsure about the correct way to ...

Unreliable Raycasting with Three.js

I am attempting to identify clicks on my Plane mesh. I have established a raycaster using provided examples as instructions. Below is the code snippet: http://jsfiddle.net/BAR24/o24eexo4/2/ Clicks made below the marker line do not register, even if they ...

Adjust the sequence of the series in dimple's multi-series chart using interactive features

My latest project involves a unique dimple interactive chart featuring two series: a pie series and a line series based on the same dataset. You can view the chart at dimplejs.org/advanced_examples_viewer.html?id=advanced_interactive_legends Check out the ...

Using JavaScript to create an array within an object and adding new elements to the array

I'm just beginning to learn programming and experimenting with React. I have a function called addComment that is triggered when a user adds a comment to a news article. At this point, I need to create a property called comments (an array) and either ...

Tips for increasing a numerical value with jQuery within a footnote extension for redactor.js

Currently, I am in the process of developing a plugin for redactor.js that will enable users to include footnotes. The end goal is to have these footnotes stored in a separate table in the database; however, as of now, it's just a mockup for a larger ...

Preventing the Sending of Origin Header in Angular 2

I am facing an issue in my Angular2 project where the HTTP service is automatically adding the 'Origin' header with a value to all of the requests. Is there a way to stop Angular2 from including this 'Origin' header in the HTTP calls? A ...

Transforming intricate JavaScript objects into JSON format using Node.js

Currently, I am engaged in a web scraping project and my goal is to construct a JSON object from the gathered data. Below is an outline of the steps I am taking to achieve this: var submitButton = driver.findElement(By.className('btn btn-primary& ...

Displaying various results using a range slider

I really need some assistance in making this range slider produce multiple outputs. I've attempted a few different options, but unfortunately, I haven't been able to figure it out. My goal is to have the text "590" display as 5.9 times the value ...

Uploading files with Express JS 4.x using Multer

I am facing challenges while attempting to upload an image in Express JS using the Multer middleware. The process seems straightforward, yet I encounter multiple issues with what should be the simplest scenario. Upon trying to execute my code, the only er ...

Streamlining all icons to a single downward rotation

I am currently managing a large table of "auditpoints", some of which are designated as "automated". When an auditpoint is automated, it is marked with a gear icon in the row. However, each row also receives two other icons: a pencil and a toggle button. W ...

Passing the title of a page as data to a component in Next.js

I am currently working on setting a custom title for each page within my next.js project. Here is an example of a simple Layout: const MainLayout = props => { return ( <Layout style={{ minHeight: "100vh" }}> <Head> < ...

What is the purpose of adding node_modules to a .gitignore file when you can easily install it from npm anyway?

It appears that excluding the node_modules folder only complicates the process for anyone downloading a project as they will need to execute either npm install or yarn ...

Adding options for a select tag from JavaScript can be accomplished by using the DOM manipulation methods

I am working on a form that includes drop-down menus. The options for the select tag need to change dynamically based on the id value. For instance, if the id is 1, the select tag options should be cat and dog. If the id is 2, the options should be apple ...

Using JavaScript to utilize a variable containing a .match method with Regex Expression

Recently, I started delving into the world of regex with the aim of incorporating variables in my matches. Imagine I have a string that reads "Total: $168" My goal is to extract just the numerical value; 168. This is what I currently have: totalCost = t ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

Selecting images using jQuery

Currently, I am in search of a jQuery image picker plugin that possesses the following features: Show a collection of images and enable the user to select one (and only one) by clicking on it If the user dislikes any of the pre-defined images, they shoul ...

When a user connects to Node.js using sockets, the previous messages are loaded. However, a bug causes the messages to be loaded to all chat users, instead of just the

New to node.js, I am currently creating a chat application with two main files: server.js (server side) and script.js (client side). In the server.js file: socket.on('previousMessages', function (data){ db.query("SELECT * FROM messages", f ...

Issue with People Picker directive causing AngularJS validation to fail

I have implemented a SharePoint client-side people picker in my form using the directive from this GitHub repository. However, I am facing an issue where the validation of my form fails and the button remains disabled. When I remove the field, the validati ...