Node JS EJS获取URL参数

时间:2017-03-20 00:36:39

标签: node.js ejs

我正在尝试读取EJS模板中的网址参数,但是我尝试或从谷歌中读取的所有内容都无效。这是我的app.js文件的相关部分:

app.post('/account/logintoaccount', function(req, res) {
    var email = req.body.email;
    if(email === '') {
        res.redirect('https://myurl.com/account/login?e=bademail');
        return;
    }
    var password = req.body.password;
    if(password === '') {
        res.redirect('https://myurl.com/account/login?e=badpassword');
        return;
    }
    res.redirect('https://myurl.com/?email=' + email + '&pw=' + password);
});

这就是我在我的EJS文件中显示变量的地方:

<div id="title-text">
    <% if(!req.query.e) { %>
        <p>Log into your account:</p>
    <% } else if(req.query.e === "badpass") { %>
        <div class="alert alert-danger"><strong>Error</strong> incorrect password</div>
    <% } else if(req.query.e === "bademail") { %>
        <div class="alert alert-danger"><strong>Error</strong> unknown email address</div>
    <% } %>
</div>

如果我删除了EJS文件的这一部分,我的重定向工作正常。 URL中包含参数,一切都很好。但是,每当我尝试在我的EJS文件中以任何形式或形式使用我的URL参数时,它都会断开并给出“X是未定义的错误”。我尝试过使用'e','req.query.e','this.e','this.req.query.e'以及谷歌搜索结果提出的任何其他内容。

我的最终目标是能够阅读https://myurl.com/account/login?e=somethinghere

中的网址参数

然后检查'e'是什么。我花了最后30多分钟阅读谷歌搜索结果,但我相信他们要么已经过时了,要么我做错了。有人可以帮忙吗?谢谢你的时间

1 个答案:

答案 0 :(得分:1)

将请求传递到您的视图

app.get('/account/:action', function(req, res) { 
   res.render('account/' + req.params.action, { 
      session: req.session,
      req: req
   });
});