为何Express中使用res.send(result)会返回错误,而res.send(""+result)可正常运行?
为什么Express中
res.send(result)报错而res.send("" + result)正常? 首先来看你的场景:你写了一个实现两数相加的Express接口,核心代码如下:
app.post("/", (req, res) => { let n1 = req.body.num1 let n2 = req.body.num2 let result = Number(n1) + Number(n2) // 这里直接用res.send(result)会报错 res.send("" + result) // 拼接空字符串后正常 })
当你直接调用res.send(result)时,会抛出如下错误:
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)
问题根源:Express的res.send()参数处理逻辑
Express的res.send()方法会根据你传入的参数类型做不同的处理:
- 如果传入的是数字类型,Express会默认把它当成HTTP状态码来使用,而不是响应体内容。
- 有效的HTTP状态码范围是
100到599之间的整数,当你传入的result是比如5这种不在有效范围内的数字时,Node.js就会抛出Invalid status code的错误。
为什么"" + result能正常运行?
当你用"" + result时,相当于把数字类型的result强制转换成了字符串类型。此时Express会把这个字符串当作响应体内容来返回,不会再把它解析成状态码,因此可以正常运行。
更规范的写法
除了空字符串拼接,你还可以用更清晰的方式把数字转成字符串:
// 方法1:使用String()显式转换 res.send(String(result)) // 方法2:如果需要返回JSON格式结果,推荐用res.json() res.json(result)
res.json()会自动把数字转换成JSON格式的响应体,不需要手动转字符串,而且语义更清晰。
内容的提问来源于stack exchange,提问作者Lokesh
相关产品推荐
相关产品推荐

