What causes the express code to generate an error when an empty string is not provided?

I have a basic Express code snippet that calculates the sum of two numbers:

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 //these n1 and n2 are coming from inex.html
    let n2 = req.body.num2
    let result = Number(n1) + Number(n2)
    res.send("" + result)
})

app.listen(port, () => {
    console.log("Server is running at port 3000")
})

In res.send, when I removed the empty string and used only res.send(result), an error occurred:

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 ServerResponse.end (node:_http_outgoing:871:10)
at ServerResponse.send (C:\Users\Vandana Singh Bondil\OneDrive\Desktop\Lokesh\calculator\node_modules\express\lib\response.js:232:10)
at C:\Users\Vandana Singh Bondil\OneDrive\Desktop\Lokesh\calculator\calculator.js:17:9
at Layer.handle [as handle_request] (C:\Users\Vandana Singh Bondil\OneDrive\Desktop\Lokesh\calculator\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Vandana Singh Bondil\OneDrive\Desktop\Lokesh\calculator\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\Vandana Singh Bondil\OneDrive\Desktop\Lokesh\calculator\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\Vandana Singh Bondil\OneDrive\Desktop\Lokesh\calculator\node_modules\express\lib\router\layer.js:95:5)

Could someone explain why this error occurs?

Answer №1

When using the send function, it is important to note that the body must be...

...a Buffer object, a String, an object, Boolean, or an Array.

Although numbers are not included in this list of acceptable types, strings are. Interestingly, in version 3 of Express (and possibly still usable in later versions despite being undocumented), you could pass a response status code as the first argument. However, since 5 is not a valid response status code, the error occurs. To resolve this, simply convert your number to a string using methods such as "" + result, String(result), or result.toString().

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

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

Conditionally displaying an input model in Vue.js using v-if

Just starting to learn vue.js and I'm looking to display table data. My idea is that when the table is in display mode, it should only show the data. However, when I click on the edit button of a table row, I want that specific row to switch to edit m ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

A guide on how to apply filtering to an array in Vue using another array

Currently, I have two arrays of objects: one is named submodules and it contains a children array within it. My goal is to filter these children arrays based on another array called accessed. new Vue({ data: { submodules: [ { type: ...

Repositioning elements within the web browser

I am looking to create a web page that features: a variety of objects with distinct shapes (such as squares, rectangles, and more) the ability for users to connect these objects using arrows (see image link below) Furthermore, users should be able to mo ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...

Generate an image on Canvas using a URL link

I have a unique URL that generates canvas images with specific parameters. It functions properly when loaded in a browser. The final line of code is: window.location = canvas.toDataURL("image/png"); However, when attempting to use this URL from another ...

Missing Values in jQuery Variable

I'm having trouble with adding a link after a block of text. Although the links render fine, the href tag seems to disappear. var eventstuff = data.text; var eventElement = $("<div class='well well-sm eventsWells'>"); var deleteButton ...

How to get an empty object as a response in a NODE.JS request?

For some reason, I am attempting to send an object to my backend. Even though I can retrieve valuable information from my network's payload, my req.body consistently returns an empty object. View my issue ...

Steps to prevent uib-timepicker from automatically adjusting time based on the Browser Timezone

Currently in my database, timestamps are stored in UTC format. On the frontend, I am implementing uib-timepicker for time editing and updating purposes. However, I do not want uib-timepicker to automatically convert the time from the server's timezone ...

show data pulled from localStorage

I'm struggling to figure out how to use localStorage for the first time, specifically in storing an array of objects and displaying that information even after page refresh. Currently, I can see that it is being stored but not displayed. const book ...

Using jSLint in combination with Angular leads to an unexpected error regarding the variable "$scope"

When performing a jSLint check on my Angular-based app, I encountered an "Unexpected '$scope'" error. To replicate the issue, you can try inputting the code snippet below into jslint.com. I'm puzzled as to why the first function declaration ...

Loop through a JSON array in a React Native application

Encountering an issue while working in react native involving parsing a JSON object and iterating over a nested array. The goal is to list all profiles objects. Tried the code below but it's not fetching the profiles object. How can I print all profi ...

Identifying and fixing bugs in a React/node/express application using VS Code

My express application debugging efforts have hit a snag. I thought I had configured my IDE according to the vs code guide for version 1.13, but the breakpoints aren't working when I run the application. We are currently working on a react (redux)/no ...

Is there a way to modify the dimensions of this container? (CSS)

After performing a search and clicking on a result, a white bubble pops up on the map. I am looking to use CSS to make this bubble smaller as it is currently too large. Can anyone provide guidance on how to achieve this? ...

The issue with Selenium chromedriver is that it is failing to execute the JavaScript scripts

Normally, the page loads like this: https://i.sstatic.net/GHSb4.png However, when opened with Chrome driver via Selenium in Python, it loads like this: https://i.sstatic.net/dO3Q2.png I have been trying to figure out how to execute JavaScript scripts on ...

Distinguishing between EJS tags: <% vs <%- --%> - What sets them apart?

The EJS documentation explains the distinction between <% and <%- as follows: <% 'Scriptlet' tag, for control-flow, no output <%= Outputs the value into the template (HTML escaped) <%- Outputs the unescaped value into the templa ...

Best method for simultaneously calling multiple routes in Node.js and Express

What is the best approach for handling multiple routes simultaneously in Node.js and Express? For instance, if I have two routes defined as app.get('/', routes.views.index); and app.all('/header', routes.views.header); I want both route ...

What could be causing my JavaScript source to fail to load in an HTML document?

Currently, I am in the process of creating a basic offline dinosaur game using HTML, JS, and CSS that is well-known to everyone. I have been diligently working on it and have successfully made everything function for a few hours. However, out of nowhere, m ...

Unable to invoke functions in the child window

In my Vue page, I have a script that opens a child window using the code snippet below: this.presentation = window.open( this.$router.resolve({name:'presentation'}).href, 'child window', 'width=auto,height=auto' ) ...