segmentationfaulter
segmentationfaulter

Reputation: 1045

Removing query parameter using node.js not working

I am having this code to remove a query parameter from a url, but it is not working. Can you have a look please?

const url = require('url')

const obj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
delete obj.query.query2
const link = url.format(obj)
console.log(link) // I was expecting the removal of query2 but it didn't happen

It logged the same url as was passed above, why query2 is not removed? Thanks

Upvotes: 2

Views: 1162

Answers (4)

Navneet Garg
Navneet Garg

Reputation: 1374

You need to remove search node from object

const obj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
delete obj.query.query2
delete obj.search

const link = url.format(obj)
console.log(link)

This will return you url http://www.example.com/path?query1=val1

Upvotes: 3

Vishnu
Vishnu

Reputation: 12293

Even though you delete query2 from query object, query2 is still present in search field.

const url = require('url');

const obj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)
console.log(obj);
delete obj.query.query2
delete obj.search
console.log(obj);
const link = url.format(obj)
console.log(link)

Upvotes: 1

Alongkorn
Alongkorn

Reputation: 4207

const url = require("url")

const urlObj = url.parse('http://www.example.com/path?query1=val1&query2=val2', true)

delete urlObj.query.query2
delete urlObj.search

const newUrl = url.format(urlObj)

console.log(newUrl) // print >> http://www.example.com/path?query1=val1

Upvotes: 0

Oliver Jenkins
Oliver Jenkins

Reputation: 126

If you look at through the source for url module (https://github.com/defunctzombie/node-url/blob/master/url.js). You can see that it will look at the search node first (line 413). Remove this as well, so that the query object is evaluated.

delete obj.search;

Upvotes: 1

Related Questions