Pass the JavaScript variable and redirect swiftly

One of the functionalities I am working on for my website involves allowing users to submit a single piece of information, such as their name. Once they input their name, it is sent to the server via a post request, and in return, a unique URL is generated specifically for them.

The ultimate objective: When users navigate to mysite.com/their-unique-url, they should be directed to mysite.com/index.html. Additionally, I want the index.html page to dynamically display their name (stored in a database alongside their unique URL).

My challenge lies in figuring out how to use Express to redirect users to index.html while simultaneously passing a JavaScript variable that can be utilized by index.html.

app.get("/:unique", function(req, res){
names.findOne({ 'id' : req.params.unique }, 'name', function (err, name) {
  if (err) return console.error(err);
  res.redirect('/'); //however, I also need to pass 'name' to index.html
});

Answer №1

I discovered a solution that involves using queryString and regular expressions.

To redirect on the server-side, include querystring in the redirection:

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

On the client-side, extract variables from the querystring using regular expressions:

function grabUrlParameter(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: " + grabUrlParameter('name'));

Despite the restrictions of querystring, I am still actively seeking an alternative solution that does not involve queryString or a templating engine.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Implementing a seamless transition effect on two slideshows using jQuery's fadeslideshow

I currently have a homepage featuring a fadeslideshow with 5 slides. The fadeslideshow plugin being used can be found at http://plugins.jquery.com/project/fadeslideshow. On the homepage, there is also a menu bar with various menu items. When a user clicks ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

Learn the steps for inserting or updating data in a local JSON file solely through JavaScript

Currently, I am in the process of reading a JSON file and removing an element once it finds an exact match. My goal is to then push the remaining data back into the JSON file after deletion. readJsonFile("./objects.json", function(jsonData){ let parsedD ...

The feature of determining if an edge exists, within the dagre-d3/graphlib,

Has anyone utilized the graph.hasEdge function in dagre-d3/graphlib to check for the existence of an edge between two nodes? This API takes two arguments representing the two nodes and verifies if there is an edge connecting them. I am facing an issue whe ...

Unlocking Extended Functionality in JQuery Plugins

At the moment, I am utilizing a JQuery Plugin known as Raty, among others. This particular plugin typically operates as follows: (function($){ $.fn.raty = function(settings, url){ // Default operations // Functions ...

HTML: Launch Frameset in a Separate Tab or Window

I have encountered an issue with using FRAMESET. Situation: Within my frameset, I have a menu with 5 links. When I click on the home page, everything looks fine. However, when I open it in a new tab or window, the design is not displayed. Is there a way ...

Encountering Challenges when Implementing Next.js with Jest

When attempting to run a test in next.js using jest, an error keeps appearing: The issue may be due to the wrong test environment being used. Refer to https://jestjs.io/docs/configuration#testenvironment-string for more information. Consider utilizing the ...

What is the best way to access event.target as an object in Angular 2?

Apologies for my limited English proficiency. . I am trying to write code that will call myFunction() when the user clicks anywhere except on an element with the class .do-not-click-here. Here is the code I have written: document.addEventListener(' ...

Filling a table cell with a div that spans 100% height

I am currently working with Bootstrap and I am attempting to create three columns filled with text overlaying a rectangle. The squares within the columns should have equal height and there needs to be spacing between them. Through the use of display:table ...

Conceal the div element if the screen size drops below a certain threshold

Is it possible to hide a div element when the browser width is less than or equal to 1026px using CSS, like this: @media only screen and (min-width: 1140px) {}? If not, what are some alternative solutions? Additional information: When hiding the div eleme ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code: function doSomething(numRetries) { $.post('someURL', {retr ...

Mixing elements from the entire webpage

My goal is to create a cohesive look for the entire page by applying a background gradient to all layers. #myDIV { width: 400px; height: 400px; background-image: linear-gradient(-45deg, rgba(251, 234, 188, 1) 0%, rgba(0, 114, 136, 1) 100%); } .bl ...

Developing single-page application frontends without utilizing node or npm

As a backend java developer with experience in spring boot, I am now exploring the world of single page applications. One aspect that appeals to me about SPA frameworks, particularly Vue, is things like model-binding and the use of components and template ...

What causes inconsistencies in the functionality of flash errors?

I have been utilizing express-flash for flash messages, which was going smoothly until I implemented a redirection to req.header("Referer"). Specifically, my issue arises when attempting to add a product to a shopping cart, with the condition that it shoul ...

troubles with compatibility between bootstrap.css and IE11

I am currently developing a web application using AngularJS and bootstrap.css. While everything appears fine on Chrome, I am facing some formatting issues on both Firefox and IE11. HEAD <head> <meta charset="utf-8"> <meta http-equi ...

Is it possible to modify the class attribute of an HTML element in PHP upon clicking an input?

In this assignment, I am restricted to using only PHP and cannot incorporate JavaScript. Currently, my code is set up to detect a post from an input type="submit" and then check for empty or filled text inputs. The code currently echoes text based on the c ...

Alter the hyperlink to a different value based on a specific condition

I need help with implementing a login feature on my app. The idea is that when the user clicks the login button, it should trigger a fetch request to log in with their credentials. If the login is successful, the button's value should change to redire ...

A step-by-step guide to displaying a list with material icons in a React JS application utilizing the Material

I tried implementing a dropdown list with Material-UI, including an icon on the left side. However, after following the documentation and adding the code for the icon, the dropdown list stopped working. InputProps={{ startAdornment: ( ...

Creating dynamic cubes in Magento with interact.js within a .phtml template

I utilized the interact.js library to create this code snippet, which functions perfectly on Chrome, Firefox, and w3schools "Try it Yourself" platform (unfortunately not compatible with Edge and IE for unknown reasons). However, when I include this code wi ...