How To Pass Data From Express To .ejs File While Redirecting In Node.js
Solution 1:
According to express docs of .redirect method:
res.redirect([status,] path)
Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.
So you can't call it like that:
res.redirect('/',{Error:'block'});
Even if that method work, it'll just redirect to '/'
, which will trigger the app.get('/', function (req, res) {...}
endpoint and show the initial login page, with error message hidden.
I believe, the best way it to change last line in app.post('/login', function (req, res) {...}
to
res.render("login",{Error:"block"});
Solution 2:
You can't make a redirection after an AJAX call if you're using AJAX. Use send instead
res.send({Error:'block'});
Solution 3:
You can pass json
with res.render
method but to do with res.redirect
you can use following.
- You can use
encodeURIComponent
app.get('/user', function(req, res) { var error = encodeURIComponent('error'); res.redirect('/?user=' + error); });
- Another way is using something in the session. Link to setup Sessions
req.session['error'] = "Error";
req.redirect('/');
- You can also use
express-flash
to flash any error on page Basic example an Usage of express-flash
Post a Comment for "How To Pass Data From Express To .ejs File While Redirecting In Node.js"