How to send integers in query parameters in nodejs Express service

前端 未结 4 1162
春和景丽
春和景丽 2020-12-15 04:43

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 in

相关标签:
4条回答
  • 2020-12-15 05:16

    You can't, as HTTP has no notion of types: everything is a string, including querystring parameters.

    What you'll need to do is to use the req.query object and manually transform the strings into integers using parseInt():

    req.query.someProperty = parseInt(req.query.someProperty);
    
    0 讨论(0)
  • 2020-12-15 05:18

    You can also try

    var someProperty = (+req.query.someProperty);
    

    This worked for me!

    0 讨论(0)
  • 2020-12-15 05:24

    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);
    }
    
    0 讨论(0)
  • 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:

    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.

    0 讨论(0)
提交回复
热议问题