Reputation: 31
when i use url.parse(from the url module in node.js)it returns undefined object keys
i kept searching on internet and apparently most people use express.js so i didnt find any case similar to mine
here is the code(shortened):
var http = require('http');
var Url = require('url');
http.createServer(function(req, res) {
if (req.url != '/favicon.ico') {
var q = Url.parse(req.url, true);
console.log(req.url);
for (var key in q) {
console.log(key + ':' + q.key);
}
console.log('closing');
res.end();
}
}).listen(8080);
and the console displays this :
/?season=summer
protocol:undefined
slashes:undefined
auth:undefined
host:undefined
port:undefined
hostname:undefined
hash:undefined
search:undefined
query:undefined
pathname:undefined
path:undefined
href:undefined
parse:undefined
format:undefined
resolve:undefined
resolveObject:undefined
parseHost:undefined
closing
Upvotes: 2
Views: 1505
Reputation: 1832
You need to use the query
property of the parsed Url
like you initially had it. You just need to access the value of the query object correctly.
Check the simplified example below (Note: queryData[key]
):
const url = require('url');
const queryData = url.parse('http://127.0.0.1:8000/status?season=summer', true).query;
for (const key in queryData) {
console.log(`${key}: ${queryData[key]}`);
}
Edit:
The explanation for why you can't do something like queryData.key
is that that would try to access a property in queryData
object named 'key' and not the current key
variable value (in this case 'season').
In this instance, the queryData
object looks like this:
var queryData = {
'season': 'summer'
};
If you try to access queryData.key
it is looking for the literal key called 'key' and not the value of the variable called key
which happens to be season in the first iteration of the for in
loop. Using queryData[key]
allows you to access the value of the key assigned to the key
variable.
Upvotes: 1
Reputation: 2785
Instead of: var q = Url.parse(req.url, true).query;
you need to use var q = Url.parse(req.url, true);
.
Otherwise q will already be Url.parse().query and the reset will not work/be undefined.
Upvotes: 0