2

In the following node.js example:

var url = require('url');
var urlString='/status?name=ryan'
var parseObj= url.parse(urlString);

console.log(urlString);
var params = parseObj.searchParams;
console.log(JSON.stringify(params));

the property searchParams is undefined. I would expect searchParams to contain the parameters of the search query.

2 Answers 2

4

As you see in https://nodejs.org/dist/latest-v8.x/docs/api/url.html#url_class_urlsearchparams

searchParams is a proxy to an URL object. You must obtain a new URL complete object (with domain and protocol) and then you can use searchParams:

var url = require('url');
var urlString='https://this.com/status?name=ryan'
var parseObj= new url.URL(urlString);

console.log(urlString);
var params = parseObj.searchParams;
console.log(params);

Other way is using the query attribute (you must pass true as second parameter to url.parse):

var urlString='/status?name=ryan'
var parseObj= url.parse(urlString, true);

console.log(parseObj);
var params = parseObj.query;
console.log(params);
Sign up to request clarification or add additional context in comments.

2 Comments

I see now that there is a legacy URL API, and that url.parse() uses the legacy. What does legacy mean in this context? will it be deprecated in the future? Should we not code to the legacy api?
I think that deprecate is not the same than legacy. I supouse that legacy can be used without probles
1

It is recommended to use: var parsedUrl = new URL(request.url, 'https://your-host'); instead of url.parse

url.parse shouldn't be used in new applications. It is deprecated and could cause some security issues: as stated here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.