rap-2-h
rap-2-h

Reputation: 32028

Return (send) int with express js

If I do this with Express it fails:

res.send(13245)

It says:

express deprecated res.send(status): Use res.sendStatus(status) instead src/x.js:38:9 (node:25549) UnhandledPromiseRejectionWarning: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 13245

It's because it consider 13245 might be a status code. I want to return 13245 anyway, is there a way do do this?

Upvotes: 2

Views: 3452

Answers (4)

Yilmaz
Yilmaz

Reputation: 49501

let say you are doing a calculation and you wanna send the result.

app.post("/transaction", (req, res) => {
  const a = req.body.amount;
  const b = req.body.price;
  const total = a*b;
  res.send(total.toString());
});

Upvotes: 1

Daniel
Daniel

Reputation: 15453

You can try res.send('13245'); or you can try res.send(""+13245).

You are getting that error because Express assumes you are trying to send a status code. So you can send it as a string and Express will accept it or join it to a string and Express should think you are sending back just some plain number and yes always check the docs when you run into trouble: http://expressjs.com/en/api.html#res.send

Upvotes: 0

Francisco Payes
Francisco Payes

Reputation: 11

If you check documentation http://expressjs.com/en/api.html#res.send, the value just can be a Buffer object, a String, an object, or an Array. What if you send

res.send({ value: 13245 })

and then in the other side you just need to grab the value (e.g. body.value).

Upvotes: 0

rap-2-h
rap-2-h

Reputation: 32028

You have to return a String (see http://expressjs.com/en/api.html#res.send):

res.send('13245')

Upvotes: 5

Related Questions