在 ejs 模板中获取查询字符串



我非常喜欢nodeJS,我有以下文件作为router.js

exports.redirectlogin = function ( req, res, next ) {
// some logic
res.redirect( '/login ', {redirecturl: req.originalUrl} );
};

我将req.originalUrl作为查询字符串传递。现在我想login.ejs文件中访问它。我尝试了以下方法,但没有一种奏效:

<div class="col-xs-6 log-in margin-20">Log In</div>
<form class="margin-20" method="POST" action="/login">
// some code
<input name="redirecturl1" type="hidden" value="<%= redirecturl %>" />
<input name="redirecturt2" type="hidden" value=<%= redirecturl %> />
<input name="redirecturl3" type="hidden" value=<% redirecturl %> />
// some code
</form>
</div>

但是我收到一个错误,因为redirecturl在所有这些情况下都没有定义。在 ejs 文件中获取它的正确方法是什么?

您正在使用 res.redirect,这会将用户发送到新的 URL,它不会进行任何模板构建。在这种情况下,您需要将代码添加到/login路由中,以从req对象中提取redirecturl,然后将其推送到/loginres.render调用中的模板中。例如在app.get('login'...);内部

app.get('/login', function(req, res, next) {
const redirectUrl = req.params.redirecturl;
return res.render('pages/login', {redirecturl: redirectUrl });
});

最新更新