Using 'querystring.parse' built-in module's method in Node.JS to read/parse parameters

别等时光非礼了梦想. 提交于 2019-12-22 13:07:27

问题


Scenario: Consider the following code:

var querystring = require('querystring');
var ParamsWithValue = querystring.parse(req._url.query);

Then I am able to read any query string's value.
E.g: If requested string is http://www.website.com/Service.aspx?UID=Trans001&FacebookID=ae67ea324
I can get the values of query string with codes ParamsWithValue.UID & ParamsWithValue.FacebookID respectively.

Issue: I am able to get the values of any number of parameters passed in the same way described above. But for second time onwards I am getting the following error in response on browser.

Error:

{"code":"InternalError","message":"Cannot read property 'query' of undefined"}

Question: What is wrong in the approach to read the query string from the URL.

Note: I don't want to use any frameworks to parse it. I am trying to depend on built-in modules only.


Update: It responds correctly when the value of any of the parameter is changed. But if the same values requested again from even different browser it throws same error.

回答1:


  1. I think you need req.url rather than req._url.
  2. req.url is a string, if you want a URI instance use require('url').parse(req.url)
  3. So, you should finally have:

    var ParamsWithValue = querystring.parse(require('url').parse(req.url).query);

Edit: I corrected a typo in point 1, the last req.url -> req._url



来源:https://stackoverflow.com/questions/15896609/using-querystring-parse-built-in-modules-method-in-node-js-to-read-parse-para

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!