简体   繁体   English

如何自定义express.js url查询参数解析

[英]How to customize express.js url query parameter parsing

So, req.query returns the hash of the query parameters. 因此, req.query返回查询参数的哈希值。 Even better, if a parameter is actually a json object, then it parses it into the respective json, which is awesome. 甚至更好的是,如果参数实际上是一个json对象,则它将其解析为相应的json,这真棒。

However, how can I customize this parsing? 但是,如何自定义此解析? For instance, I would like a certain value to be parsed as a number, rather than as a string. 例如,我希望将某个值解析为数字而不是字符串。 Surely, I can do it post factum and modify the returned object. 当然,我可以在制造后执行此操作并修改返回的对象。 But, I am interesting to know whether the process can be customized in general. 但是,我很想知道该流程是否可以总体上进行定制。

EDIT 编辑

For example, consider the following request: 例如,考虑以下请求:

GET http://localhost:8000/admin/api/inventory?rowsPerPage=25&page=0&q%5Bqty%5D%5B%24lt%5D=100 

Decoding it we get: 对其进行解码,我们得到:

GET http://localhost:8000/admin/api/inventory?rowsPerPage=25&page=0&q[qty][$lt]=100

Now, express converts these query parameters to 现在,express将这些查询参数转换为

req.query = {rowsPerPage: "25", page: "0", q: {qty: {$lt: "100"}}

My problem is with "25", "0" and "100" - I want them to be numbers. 我的问题是“ 25”,“ 0”和“ 100”-我希望它们是数字。 So, I can either change the req.query post factum or interfere with the parsing process. 因此,我可以更改req.query发布后的结果,也可以干扰解析过程。 I want to learn the latter. 我想学习后者。

the query string is parsed here connect-query.js which is based on tj's querystring parser node-querystring you may want to look into that or into nodes querystring parser. 查询字符串将在此处connect-query.js进行解析,它基于tj的querystring解析器node-querystring,您可能要查看该查询或节点querystring解析器。 AFAIK u cannot change the qs parsing without forking express and changing something in there. AFAIK u无法在不派发express和更改其中内容的情况下更改qs解析。 anyways handling this cases in a middleware or later on in your app where you need the strings to be numbers would be better performance wise instead of checking for numbers in every request. 无论如何,在需要字符串为数字的中间件中或以后在应用程序中处理这种情况,在性能上都比不检查每个请求中的数字更好。

You should have a look at the req.query middleware provided by connect . 你应该看看req.query提供中间件连接 It is based on node-querystring . 它基于node-querystring

This is how I do it (using CoffeeScript and Lodash): 这是我的方法(使用CoffeeScript和Lodash):

app.use (req, res, next) ->
  # Ensure all integer parameters are parsed correctly.
  _.each req.query, (value, key) ->
    unless isNaN value
      req.query[key] = _.parseInt value
  next()

The same can easily be achieved with JavaScript and no extensions. 使用JavaScript无需扩展即可轻松实现相同的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM