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
I've tried doing the following, but it produces the same link, without the new
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.
If you look at the latest documentation, you can see that
url.format behaves in the following way:
searchwill be used in place of
query(object; see querystring) will only be used if
And when you modify
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.
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));