Search code examples
node.jsurlurl-parametersurl-parsing

Proper way to Extract parameters from a URL in a Node.JS app


I have code in a Node.JS app, only partly working.

Though I think I have figured out in which case there are problems, I do not know the proper solution to fix it.

Here is the relevant code for the question:

  app.get('/Path', (req, res) => {
    .....
    let kickVal = req.url.substring(9,14) // Extracting a 5 digits string from the URL.
    // Instead of the line above, I have also tried to use querystring to get the value for kickVal, but it did not work any better.
    .....
    doSomeUsefulStuff(res,kickVal)
  })
  
  function doSomeUsefulStuff(response,kickStr=null) {
    ... do some work using kickStr ...
    // Here kickStr does not always shows up as expected.
  }

For example when using:

http://localhost:3000/Path?fp=10234

http://localhost:3000/Path?fp=31204

then all is fine I get the values, 10234 and 31204 for kickStr inside doSomeUsefulStuff as one would expect.

But when using:

http://localhost:3000/Path?fp=01243

http://localhost:3000/Path?fp=04231

I get 675 in the first case and 2201 in the second, when I expected the strings '01243' and '04231'.

Generally speaking when the string of digits contains a leading zero, things go wrong. I suspect that is because req.url is not a simple string as I would like it to be. But what is the correct way to solve this issue?

It should be noted that I do not do any kind of conversion to or from Int. The code above (kickVal = req.url.substr...) is the only thing I do to extract the value (kickVal). Why is this not working is certainly my first question.


Solution

  • I finally found out what was making things go wrong. I needed to put quotes around kickVal.

    In other words, instead of this line of code:

    doSomeUsefulStuff(res,kickVal)
    

    I had to use this one:

    doSomeUsefulStuff(res,"'"+kickVal+"'")
    

    And all was solved.