Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 .ejs that password is wrong.Below are the detail

Here is my app.js file code- Here i am sending one json and hiding that invalid password in .ejs file

 app.get('/', function (req, res) {

     res.render("login",{Error:"none"});

});

app.post('/login', function (req, res) {

    var username = req.body.username;
    var password = req.body.password;
     //Here will be my code to check detail wrong or right
     res.redirect('/',{Error:'block'});
}

Here is my login.ejs file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="css/style.css" type="text/css" />
    <link rel="stylesheet" href="css/font.css" type="text/css" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>
    <div class="Error" id="error" style="display:<%=Error%>;">Invalid email/phone or password</div>
    <div class="Body">
        <form class="LogBox" action="/login" method="post">
            <div class="Head">Log In</div>
                <input type="text" placeholder="Email or Phone" class="inputfrontbutton" name="username">
                <input type="password" placeholder="Password"  class="inputfrontbutton" name="password">
                <input type="submit" value="Log In" class="frontsubmit">
        </form>
    </div>
</body>

</html>

But I am unable to send json data in redirect.Is there any way i can do this?

like image 416
Nitesh Sharma Avatar asked Oct 18 '25 16:10

Nitesh Sharma


1 Answers

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"});
like image 132
im.pankratov Avatar answered Oct 21 '25 06:10

im.pankratov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!