快速路由参数与 HTTP 查询参数

Express route parameters vs HTTP query parameters

一直想知道下面是什么记号,

GET /user/:name/books/:title

以及如何解释直到最近,当我了解到它们是Express route的形式并且带有":"的是Express route参数。

所以我没有找到答案的问题来了,比方说,

问题是,如果大部分甚至所有参数都是可选的呢?如何使用 Express 路由处理?

问题是,使用 HTTP 查询参数,例如

https://example.org/?page=2&limit=3&sort=price

查询参数的顺序可以是任意的,而对于 Express 路由,在我看来,路由参数必须以非常严格的方式指定 way/order。那么如果所有的路由参数都是可选的,而我只需要指定最后一个呢? (无论路由参数顺序怎么排,总有最后一个)

我确实知道 Express 可以处理 querystring.parse(parsedUrl.query),但我问这个问题的原因真的是因为这个 -- https://github.com/gofiber/docs/blob/master/original/routing.md#parameters

即gofiber follows/uses处理路由参数的Express路由约定,我需要所有路由参数都是可选的。

如何处理?

您在 URL 中使用 : 发送的每个变量都通过 req.params

接收

This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.

// will be available in route in req.params object
router.get('/somepath/with/:variable', (req ,res) => {
  console.log(req.params.variable);
});

您在 ?(查询参数)之后在 URL 中发送的每个变量都将在 req.query

中可用

This property is an object containing a property for each query string parameter in the route. When query parser is set to disabled, it is an empty object {}, otherwise it is the result of the configured query parser.

// will be available in route in req.query object
router.get('/somepath/with/variables?page=2&limit=3&sort=price', (req ,res) => {
  console.log(req.query.page);
  console.log(req.query.limit);
  console.log(req.query.sort);
});

您通过 ajax 或表格或类似的东西发送的所有数据都将通过 req.body

收到

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().

// will be available in route in req.body object
router.get('/somepath/with/variables', (req ,res) => {
  // send in request body like for example form data:
  console.log(req.body.variable1) // i.e
});

这是三个以三种不同方式收集数据的对象。 您应该只选择适合您场景的内容。我猜 Route params 不是正确的选择,当变量随机到达时你应该使用 req.query 但是一旦你在相应的对象中解析它们你应该知道如何处理它们。

我希望我理解了问题并澄清了。