Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

no response received when sending integer value as response to NodeJS API call

I am trying to send some integer value as response after making call to API Endpoint.
This is sample code to illustrate the problem:

app.post('/add5', (req, res) => {
  result = req.body.num + 5;
  res.send(result);
});

And this is the request payload:

{
  "num": 7
}

Expected output: 12

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But following output logged in terminal and no(blank) response is received.

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 12
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.writeHead (node:_http_server:272:11)
    at ServerResponse._implicitHeader (node:_http_server:263:8)
    at ServerResponse.end (node:_http_outgoing:871:10)
    at ServerResponse.send (/storage/emulated/0/codes/api/node_modules/express/lib/response.js:221:10)
    at /storage/emulated/0/codes/api/index.js:208:7
    at Layer.handle [as handle_request] (/storage/emulated/0/codes/api/node_modules/express/lib/router/layer.js:95:5)
    at next (/storage/emulated/0/codes/api/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/storage/emulated/0/codes/api/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/storage/emulated/0/codes/api/node_modules/express/lib/router/layer.js:95:5)

But, adding some string in the string works totally fine.

app.post('/add5', (req, res) => {
  result = req.body.num + 5;
  res.send("Result: " + result);
});

This returns expected output i.e. Result: 12

>Solution :

Use res.json(result) or res.send(JSON.stringify(result)) or res.send(200, result). Otherwise express assumes that you’re passing a http status code to send, as the error message signifies. Or upgrade to express 4, where this cannot happen any more.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading