1

I'm working on a app in Node/Express/Jade environment.

Let's assume I start my app, and direct my browser to this URL:

/superadmin/?year=2012

On this page, i find a list with object, sorted in a default order. Here is also a link that will re-sort the list objects in another order. I jade this link look like:

a(href = '?sortAfter=company&ascending=1') Company

If i press this link, I will get the items sorted in the way I want, but the ?year=2012 from earlier query string will be lost.

Question: How do I re-write this link to add the new query strings, and not replace it.

Anders Östman
  • 3,702
  • 4
  • 26
  • 48
  • 1
    Why dont you just add the year on the end of your link string a(href = '?sortAfter=company&ascending=1&year=2012') – Dominic Green Oct 28 '13 at 13:15
  • 1
    Have a look at http://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-node-js – plalx Oct 28 '13 at 13:19
  • 1
    ^^^ What Dominic said, something like `href='?stuff' + '&year=' + req.body.year` – adeneo Oct 28 '13 at 13:19
  • 1
    You need to manually append the query string to the URL. There is no native way browsers can interpret you just want to add a query string parameter to the end of an URL keeping the same structure as before, but you can write some JavaScript code to do that. – Guilherme Sehn Oct 28 '13 at 13:21

2 Answers2

1

Got the same problem, here's how I fixed it:

Installed https://npmjs.org/package/URIjs via npm install URIjs Now, in your route :

var URI = require('URIjs');
app.get('/', function(req, res) {;
    res.render('views/index.jade', {
        urlHelper: function (key, value) {
           return (new URI(req.url)).setQuery(key, value);
        }
    });
};

And in jade :

a(href=linkHelper('acesnding',1)) Company
Vinz243
  • 9,654
  • 10
  • 42
  • 86
0

I've come up with my own npm package for just this cause -> https://www.npmjs.com/package/qsm

Example:

var qsm = require('qsm');

app.get('/', (req, res) => {
    res.render('views/index.jade', {
        addQueryString: (key, value) => {
            return qsm.add(window.location.href, [{ query: key, value }]);
        }
    });
});

and in jade

a(href= addQueryString('acesnding',1)) Company

Please refer the README in qsm and you'll see how easy it is to append querystring, remove specific querystrings and even parse and much more!

You can even clear, remove and replace querystrings. The best of all, it doesn't have to be a URL, it can be whatever string you can think of, but it will behave as that string is an url and append querystring to it: e.g: ?key=value or &key=value depending on what is already present.