0

I would like to add an optional referral parameter to every URL of my node.js app. I could do the following, but I am thinking about a more efficient/elegant way of achieving this, so my code won't end being too long unnecessarily:

app.get('/product/:example/', function (req, res) {
  res.render('product.ejs', { product : product[req.param('example')] });
});

app.get('/product/:example/referrer/:user/', function (req, res) {
  // do referral stuff
  res.render('product.ejs', { product : product[req.param('example')] });
});

I am thinking about something like this (which obviously doesn't work):

app.get('/product/:example/',  function (req, res) { ... });
app.get('/category/:example/', function (req, res) { ... });
// set up all GET requests ...

app.get('/*/referrer/:user/', function (req, res, next) {
  // do referral stuff
  req.next();
});

Thanks!

Jorge

EDIT: Thank you for your response, mvuajua. I played around with it and I figured out the following. I hope this will help someone:

app.use(function(req, res, next) {
  if (req.url.search('/referrer/') > -1) {
    res.redirect(req.url.substring(0, req.url.search('/referrer')));
    var referrer = req.url.substring(req.url.search('/referrer/')+10,req.url.length);
    // do stuff with referrer;
  } else {
    next();
  }
});

1 Answer 1

2

You can use a middleware, something like

app.use(function(req, res, next) {
    // do stuff here
    next();
});

You can also scope it to specific routes, with regular expressions if needed (not sure if that one will work, play around with it a bit until it fits your needs):

app.use(/(.*)\/referrer\/(.*)/, function(req, res, next) {
    // do stuff here
    next();
});

You still need to account for the parameter in your routes though (or they won't match), or do a redirect in the middleware to the url without the referrer part.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.