使用Node.JS中的'querystring.parse'内置模块的方法读取/解析参数
场景: 考虑以下代码:
var querystring = require('querystring');
var ParamsWithValue = querystring.parse(req._url.query);
然后,我就能读取任何查询字符串的值.
例如:如果请求的字符串是 http://www.website.com/Service.aspx?UID=Trans001&FacebookID=ae67ea324
我可以使用代码ParamsWithValue.UID
&获取查询字符串的值. ParamsWithValue.FacebookID
.
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.
错误:
{"code":"InternalError","message":"Cannot read property 'query' of undefined"}
问题:从URL读取查询字符串的方法出了什么问题.
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.
-
我认为您需要req.url而不是req._url.
I think you need req.url rather than req._url.
req.url是一个字符串,如果要使用URI实例,请使用require('url').parse(req.url)
req.url is a string, if you want a URI instance use require('url').parse(req.url)
所以,您最终应该拥有:
So, you should finally have:
var ParamsWithValue = querystring.parse(require('url').parse(req.url).query);
我更正了第1点的错字,即最后一个req.url->. req._url
I corrected a typo in point 1, the last req.url -> req._url