javascript - 如果我不提供空字符串,为什么 express 代码会返回错误?

我有一个简单的 express 代码,它添加了两个数字:

const express = require('express')
const bodyParser = require('body-parser')

const app = express()
const port = 3000

app.use(bodyParser.urlencoded({ extended: true }))

app.get('/', (req, res) => {
    res.sendFile(__dirname + "/index.html")
})

app.post("/", (req, res) => {
    let n1 = req.body.num1 //these n1 and n2 are coming from inex.html
    let n2 = req.body.num2
    let result = Number(n1) + Number(n2)
    res.send("" + result)
})

app.listen(port, () => {
    console.log("Server is running at port 3000")
})

res.send 中,如果我删除了空字符串并仅键入 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)

谁能告诉我为什么代码有效???

回答1

因为 https://expressjs.com/en/4x/api.html#res.send 要求 body 是...

...Buffer 对象、String、对象、BooleanArray

数字不在该列表中,但字符串在。虽然它在 v4(更高版本)中没有记录,但在 https://expressjs.com/en/3x/api.html#res.send 中,您可以将响应状态代码(如 200 或 404)作为第一个参数传递,显然它仍然支持这样做(尽管没有记录)您正在使用的版本,可能是为了支持遗留项目。 5 不是有效的响应状态代码,因此您会收到错误消息。您必须将您的数字转换为字符串。 "" + result 是一种方法。其他是 String(result)result.toString()

相似文章