1

I have a site where I want to allow users to submit a single piece of information (for simplicity, let's assume their name). They submit their name, this is sent to the server with a post request, and a unique url is returned for them.

The goal: when users go to mysite.com/their-unique-url, then it takes them to mysite.com/index.html, modified so that their name (stored in a database with their unique url) shows up on the page.

How can I have express redirect users to the index.html and, while doing so, pass a JavaScript variable for index.html to use?

app.get("/:unique", function(req, res){
names.findOne({ 'id' : req.params.unique }, 'name', function (err, name) {
  if (err) return console.error(err);
  res.redirect('/'); //but I also want to pass 'name' to index.html
});
Sam
  • 705
  • 1
  • 9
  • 18
  • res.render takes a view/template file (.pug, depending on your templating engine) and renders it with the context provided in the object in the second argument. There's no need to pass it a callback. – perfect5th Jul 14 '17 at 13:46
  • Possible duplicate of https://stackoverflow.com/questions/19035373/how-do-i-redirect-in-expressjs-while-passing-some-context ? – perfect5th Jul 14 '17 at 13:47
  • @perfect5th is it possible to achieve what im trying to without using a template engine? – Sam Jul 14 '17 at 14:03

1 Answers1

0

The solution that I found is to use queryString & regular expressions.

Server-side, add querystring to redirect:

res.redirect('/?name=' + name);

Client-side, access variable from querystring using regular expression:

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
console.log("name: " + getUrlParameter('name'));

However, due to limitations of querystring, I am still looking for a solution that does not uses queryString nor a templating engine.

Sam
  • 705
  • 1
  • 9
  • 18