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
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
CodePudding user response:
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.