adamM
adamM

Reputation: 1156

url.searchParams returns undefined in node.js

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.

Upvotes: 2

Views: 6039

Answers (2)

norbux
norbux

Reputation: 11

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

Upvotes: 1

Emilio Platzer
Emilio Platzer

Reputation: 2469

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);

Upvotes: 4

Related Questions