0

I want to send user object to specific route before redirecting to that route . I have tried this solution res.locals.var but its returning undefined .

I am redirecting user from signup route to lounge route .

Here is the code - https://pastecord.com/mecyheducu.js I am stuck at this for the whole day now

Tjsm
  • 5
  • 3

1 Answers1

0

You can use several ways:

  • Send it in the URL you cannot directly pass a complete JavaScript object in the URL. However, you can serialize the object into a format that can be sent as a query parameter, such as JSON or URL encoding.

Here's an example of how you can serialize a JavaScript object into JSON and send it as a query parameter during a redirect:

app.get('/redirect', function(req, res) {
  var data = {
    name: 'Mohammed',
    age: 25,
  };

  var serializedData = encodeURIComponent(JSON.stringify(data));
  res.redirect('/next-route?data=' + serializedData);
});

app.get('/next-route', function(req, res) {
   var serializedData = req.query.data;
   var data = JSON.parse(decodeURIComponent(serializedData));
   // Use the data as needed
   res.send(data);
});
  • Send it in session You need to use session middleware such as express-session, you can store the complete JavaScript object in a session variable and access it in the redirected request. Here's an example:

    app.get('/redirect', function(req, res) {
       var data = {
         name: 'Mohammed',
         age: 25,
       };
    
       req.session.myData = data;
       res.redirect('/next-route');
     });
    
     app.get('/next-route', function(req, res) {
       var data = req.session.myData;
       // Use the data as needed
       res.send(data);
     });
    

Make sure you have set up the session middleware correctly before using this approach. You need to configure and initialize the session middleware in your Express application. Here's a basic example:

const session = require('express-session');
app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true
}));