如何在nodejs Express服务中的查询参数中发送整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20355876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send integers in query parameters in nodejs Express service
提问by kishore
I have a nodejs express web server running on my box. I want to send a get request along with query parameters. Is there any way to find type of each query parameter like int,bool,string. The query parameters key value is not know to me. I interpret as a json object of key value pairs at server side.
我的机器上运行着一个 nodejs express web 服务器。我想发送一个 get 请求和查询参数。有没有办法找到每个查询参数的类型,比如 int、bool、string。我不知道查询参数键值。我在服务器端解释为键值对的 json 对象。
回答by Paul Mougel
You can't, as HTTP has no notion of types: everything is a string, including querystring parameters.
你不能,因为 HTTP 没有类型的概念:一切都是一个字符串,包括查询字符串参数。
What you'll need to do is to use the req.queryobjectand manually transform the strings into integers using parseInt():
您需要做的是使用该req.query对象并使用以下方法手动将字符串转换为整数parseInt():
req.query.someProperty = parseInt(req.query.someProperty);
回答by parvezp
You can also try
你也可以试试
var someProperty = (+req.query.someProperty);
This worked for me!
这对我有用!
回答by Rori Stumpf
As mentioned by Paul Mougel, http query and path variables are strings. However, these can be intercepted and modified before being handled. I do it like this:
正如 Paul Mougel 所提到的,http 查询和路径变量是字符串。但是,这些可以在处理之前被拦截和修改。我这样做:
var convertMembershipTypeToInt = function (req, res, next) {
req.params.membershipType = parseInt(req.params.membershipType);
next();
};
before:
前:
router.get('/api/:membershipType(\d+)/', api.membershipType);
after:
后:
router.get('/api/:membershipType(\d+)/', convertMembershipTypeToInt, api.membershipType);
In this case, req.params.membershipType is converted from a string to an integer. Note the regex to ensure that only integers are passed to the converter.
在这种情况下, req.params.membershipType 从字符串转换为整数。请注意正则表达式以确保仅将整数传递给转换器。
回答by hierd
Maybe this will be of any help to those who read this, but I like to use arrow functions to keep my code clean. Since all I do is change one variable it should only take one line of code:
也许这会对阅读本文的人有所帮助,但我喜欢使用箭头函数来保持我的代码整洁。因为我所做的只是改变一个变量,所以它应该只需要一行代码:
module.exports = function(repo){
router.route('/:id,
(req, res, next) => { req.params.id = parseInt(req.params.id); next(); })
.get(repo.getById)
.delete(repo.deleteById)
.put(repo.updateById);
}

