如何在同一路由中的 Express 中添加多个可选参数
How do I add multiple optional parameters in Express in same route
Whosebug 的铁杆粉丝,这是我关于它的第一个问题!我正在从事一个 javascript 快递项目,并试图弄清楚我是否可以在一个 get 请求下做到这一点。我很难弄明白这一点
app.get("/test/:q1&:q2&:q3", (req, res) => {
console.log(req.params)
})
基本上,当用户查找以下路由时,我希望在发出这些 get 请求时在 req.params 中得到以下结果。如果可能,我想将其保留在一个获取请求下。
澄清一下。上面的代码可以更改以满足下面的功能要求。以下无法更改
"http://localhost:3000/test/hello" --->
req.params will equal { q1: "hello" }
"http://localhost:3000/test/hello&world" --->
req.params will equal { q1: "hello", q2: "world" }
"http://localhost:3000/test/hello&world&foobar" --->
req.params will equal { q1: "hello", q2: "world", q3: "foobar" }
我试过使用“?”在查询中,但它似乎只适用于后跟“/”的新路线,而不是在同一路线内。我在想我将不得不采用快速而肮脏的解决方案,即为每个场景再发出 2 个 get 请求。目前,当我尝试输入“/test/hello&world”或“/test/hello”时,它会崩溃,并且只有在我填满所有 3 个部分时才会工作。
你能试试这个吗?
app.get('/test/:string', (req, res) => {
const str = req.params.string
const params = str.split('&')
.reduce((acc, curr, i) => ({ ...acc, [`q${i + 1}`]: curr }), {})
// params => { q1: 'hello', q2: 'world', q3: 'foobar' }
})
Whosebug 的铁杆粉丝,这是我关于它的第一个问题!我正在从事一个 javascript 快递项目,并试图弄清楚我是否可以在一个 get 请求下做到这一点。我很难弄明白这一点
app.get("/test/:q1&:q2&:q3", (req, res) => {
console.log(req.params)
})
基本上,当用户查找以下路由时,我希望在发出这些 get 请求时在 req.params 中得到以下结果。如果可能,我想将其保留在一个获取请求下。
澄清一下。上面的代码可以更改以满足下面的功能要求。以下无法更改
"http://localhost:3000/test/hello" --->
req.params will equal { q1: "hello" }
"http://localhost:3000/test/hello&world" --->
req.params will equal { q1: "hello", q2: "world" }
"http://localhost:3000/test/hello&world&foobar" --->
req.params will equal { q1: "hello", q2: "world", q3: "foobar" }
我试过使用“?”在查询中,但它似乎只适用于后跟“/”的新路线,而不是在同一路线内。我在想我将不得不采用快速而肮脏的解决方案,即为每个场景再发出 2 个 get 请求。目前,当我尝试输入“/test/hello&world”或“/test/hello”时,它会崩溃,并且只有在我填满所有 3 个部分时才会工作。
你能试试这个吗?
app.get('/test/:string', (req, res) => {
const str = req.params.string
const params = str.split('&')
.reduce((acc, curr, i) => ({ ...acc, [`q${i + 1}`]: curr }), {})
// params => { q1: 'hello', q2: 'world', q3: 'foobar' }
})