benui
benui

Reputation: 6828

Node.js url.parse result back to string

I am trying to do some simple pagination. To that end, I'm trying to parse the current URL, then produce links to the same query, but with incremented and decremented page parameters.

I've tried doing the following, but it produces the same link, without the new page parameter.

var parts = url.parse(req.url, true);
parts.query['page'] = 25;
console.log("Link: ", url.format(parts));

The documentation for the URL module seems to suggest that format is what I need but I'm doing something wrong.

I know I could iterate and build up the string manually, but I was hoping there's an existing method for this.

Upvotes: 20

Views: 47342

Answers (4)

d1b1
d1b1

Reputation: 144

To dry out code and get at URL variables without needing to require('url') I used:

/* 
   Used the url module to parse and place the parameters into req.urlparams.
   Follows the same pattern used for swagger API path variables that load 
   into the req.params scope.

*/
  app.use(function(req, res, next) {
    var url = require('url');
    var queryURL = url.parse(req.url, true);
    req.urlparams = queryURL.query;
    next();
  });

var myID = req.urlparams.myID;

This will parse and move the url variables into the req.urlparams variable. It runs early in the request workflow so is available for all expressjs paths.

Upvotes: 0

Marcel M.
Marcel M.

Reputation: 2376

Seems to me like it's a bug in node. You might try

// in requires
var url = require('url');
var qs = require('querystring');

// later
var parts = url.parse(req.url, true);
parts.query['page'] = 25;
parts.query = qs.stringify(parts.query);
console.log("Link: ", url.format(parts));

Upvotes: 3

ampersand
ampersand

Reputation: 4314

The other answer is good, but you could also do something like this. The querystring module is used to work with query strings.

var querystring = require('querystring');
var qs = querystring.parse(parts.query);
qs.page = 25;
parts.search = '?' + querystring.stringify(qs);
var newUrl = url.format(parts);

Upvotes: 2

Alex Turpin
Alex Turpin

Reputation: 47776

If you look at the latest documentation, you can see that url.format behaves in the following way:

  • search will be used in place of query
  • query (object; see querystring) will only be used if search is absent.

And when you modify query, search remains unchanged and it uses it. So to force it to use query, simply remove search from the object:

var url = require("url");
var parts = url.parse("http://test.com?page=25&foo=bar", true);
parts.query.page++;
delete parts.search;
console.log(url.format(parts)); //http://test.com/?page=26&foo=bar

Make sure you're always reading the latest version of the documentation, this will save you a lot of trouble.

Upvotes: 53

Related Questions