在node.js中重定向时如何将数据从express传递到.ejs文件 [英] How to pass Data from express to .ejs file while redirecting in node.js

查看:57
本文介绍了在node.js中重定向时如何将数据从express传递到.ejs文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在填写信息后单击提交时在login.ejs文件中登录表单,如果详细信息正确,则将重定向到页面,否则我想在.ejs中显示密码错误的信息.以下是详细信息

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

这是我的app.js文件代码-在这里,我发送一个json并将该无效密码隐藏在.ejs文件中

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'});
}

这是我的login.ejs文件

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>

但是我无法重定向发送json数据.有什么办法可以做到这一点?

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

推荐答案

据此表示

res.redirect([状态,]路径)

res.redirect([status,] path)

重定向到从具有指定状态的指定路径派生的URL,该状态为与HTTP状态码对应的正整数.如果未指定,则状态默认为"302"已找到".

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'});

即使该方法有效,它也会重定向到'/',这将触发 app.get('/',function(req,res){...} 端点并显示初始登录页面,并隐藏错误消息.

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.

我认为,最好的方法是将 app.post('/login',function(req,res){...} 的最后一行更改为

I believe, the best way it to change last line in app.post('/login', function (req, res) {...} to

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

这篇关于在node.js中重定向时如何将数据从express传递到.ejs文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆