3

In my nodejs and "express" application I have this:

app.get("/:page?", function (req, res) {
  var pg = req.params.page;

which corresponds to localhost:123 or localhost:123/3.

However, I want to be able to get the current page the same way by req.params.page, but the url should be localhost:123 or localhost:123/?page=X.

How?

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
Mario
  • 185
  • 9
  • You want to make the query string part of the routing; is that right? I'm pretty sure you can't do that, but it's an good question. This might be your closest duplicate: [Pre-routing with querystrings with Express in Node JS](http://stackoverflow.com/questions/14909465/pre-routing-with-querystrings-with-express-in-node-js) – apsillers Mar 01 '16 at 16:12
  • Possibly a closer duplicate: [How to parse variables in querystring using Express?](http://stackoverflow.com/questions/14669669/how-to-parse-variables-in-querystring-using-express) ("Query strings are not considered when performing these [route] matches...") – apsillers Mar 01 '16 at 16:21

2 Answers2

3

My first suggestion is that you do not define your endpoint with /:variable. This will then match any route you create that follows that pattern. You should instead use something like /pages/:page to get a specific page

Then, you should use the URL parameter functionality in Express to include a URL parameter.

Define your route like this:

app.get("/pages/:page", function (req, res) {
    var pg = undefined;

    if (req.query.page) {
        pg = req.query.page;
    }
}

You can then access the page in req.query.page if it exists and do whatever you want with that value.

So for example, you could submit a request with localhost/pages/123?page=3.

req.query.page would equal 3 and req.params.page would equal 123.

Mike
  • 10,297
  • 2
  • 21
  • 21
0

You should instead define your route without the ? and if you do a get operation, for example on localhost:123/3?this=that then the req.query.this will be populated with the value that

Osukaa
  • 708
  • 3
  • 10
  • 22