Skip to content Skip to sidebar Skip to footer

How To Pass Data From Express To .ejs File While Redirecting In Node.js

I have on login form in login.ejs file when i click on submit after filling information i am redirecting to the page if detail are correct otherwise i want to show something in .ej

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.

  1. You can use encodeURIComponentapp.get('/user', function(req, res) { var error = encodeURIComponent('error'); res.redirect('/?user=' + error); });
  2. Another way is using something in the session. Link to setup Sessionsreq.session['error'] = "Error";req.redirect('/');
  3. 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"