最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Return (send) int with express js - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Oct 2, 2018 at 13:21 rap-2-hrap-2-h 32.1k47 gold badges188 silver badges281 bronze badges 1
  • 1 Did you try res.status(200).send(13245)? – kit Commented Oct 2, 2018 at 13:32
Add a ment  | 

4 Answers 4

Reset to default 5

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

res.send('13245')

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());
});

If you check documentation http://expressjs./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).

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./en/api.html#res.send

发布评论

评论列表(0)

  1. 暂无评论