从 Node.JS 应用程序中的 URL 中提取参数的正确方法

问题描述 投票:0回答:0

我在 Node.JS 应用程序中有代码,只能部分工作。

虽然我认为我已经弄清楚在哪种情况下会出现问题,但我不知道解决它的正确解决方案。

这里是问题的相关代码:

  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.
  }

例如使用时:

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

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

然后一切都很好我得到值,1023431204 for kickStr inside doSomeUsefulStuff 正如人们所期望的那样。

但是使用时:

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

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

我在第一种情况下得到 675,在第二种情况下得到 2201,当我期望字符串 '01243''04231'.

一般来说,当数字串包含前导零时,就会出错。 我怀疑这是因为 req.url 不是我希望的简单字符串。 但是解决这个问题的正确方法是什么?

需要注意的是,我没有对 Int 进行任何类型的转换。上面的代码 (kickVal = req.url.substr...) 是我提取值 (kickVal) 的唯一方法。为什么这不起作用当然是我的第一个问题。

node.js url url-parameters url-parsing
© www.soinside.com 2019 - 2024. All rights reserved.