4

EDIT: The solutions proposed in this answer are the right way to achieve this:

On a get request in node I can do this:

app.get('/', function(req, res) {
    res.render('index.ejs', {
        message: 'test'
    });
});

And send an object in order to set a message along with the request. How can I do the same with a redirect:

i.e. something like this:

function testSend(req, res) {

    mess = {message: 'test two'};
    res.redirect('/', mess);
    //Won't pass to the "get"
}
Community
  • 1
  • 1
Startec
  • 12,496
  • 23
  • 93
  • 160
  • 1
    possible duplicate of [Redirecting in express, passing some context](http://stackoverflow.com/questions/19035373/redirecting-in-express-passing-some-context) – 0x9BD0 Nov 04 '14 at 23:34
  • can u clarify your goals? do you want that object(`mess`) to be sent as JSON to the client in the 301 HTTP response body? – mattr Nov 04 '14 at 23:36
  • My goal would be to pass a `message` such as `"please login first"` and have that be rendered in my view. – Startec Nov 04 '14 at 23:39
  • as far as I know you can't, but what one should do for something as simple as a message like this is append the query string www.redirect_url?message=your_message to the redirect. – Chris Hawkes Nov 26 '15 at 01:23

2 Answers2

8

Another solution would be using express sessions:

When you initialize your app:

var session = require('express-session');
app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false}));
//configure the options however you need them, obviously

Your redirect function:

function testSend(req, res) {
    req.session.message = 'please login first'; //or whatever
    res.redirect('/');
});

And in your router:

app.get('/', function(req, res) {
    var message = req.session.message;
    res.render('index.ejs', {message: message});
});

This keeps your message securely on the server side, in case it contains sensitive data.

Jeremy D
  • 197
  • 2
  • 13
2

You can use session like @Jeremy, or pass data like params on URL

res.redirect('/my-url/?param1=value1&param2=value2')

on controller

req.query.param1
req.query.param2
DJeanCar
  • 1,463
  • 1
  • 11
  • 13