如何在.ejs文件中获取Expreejs的req和res对象

我正在尝试使用Express js与.ejs意见。

我想redirect我的网页到任何事件的一些其他页面让说“onCancelEvent”

根据Express js文档,我可以通过使用res.redirect(“/ home”)来完成此操作。

但是我不能在我的ejs文件中获取res对象。

任何人都可以请告诉我如何访问.ejs文件中的req和res对象

请帮忙。

谢谢

简答

如果要访问EJS模板中的“req / res”,可以将req / res对象传递给控制器​​函数(特定于此请求的中间件)中的res.render():

res.render(viewName, { req : req, res : res /* other models */}; 

或者在一些服务于所有请求(包括这个请求)的中间件中设置res.locals:

 res.locals.req = req; res.locals.res = res; 

然后你将能够访问EJS中的“req / res”:

 <% res.redirect("http://www.stackoverflow.com"); %> 

进一步讨论

但是,你真的想在视图模板中使用res来redirect吗?

如果事件向服务器端发起了一些请求,它应该在查看之前通过控制器。 所以你必须能够检测到条件并发送控制器内的redirect。

如果事件只发生在客户端(浏览器端)而不发送请求到服务器,redirect可以由客户端完成javascript:

 window.location = "http://www.stackoverflow.com"; 

在我看来:你没有。

最好创build一个逻辑来决定在调用res.render()之前很久就会发生的一些中间件的redirect。

这是我的观点,你的EJS文件应该包含尽可能less的逻辑。 循环和条件是可以的,只要它们是有限的。 但所有其他的逻辑应该放在中间件中。

 function myFn( req, res, next) { // Redirect if something has happened if (something) { res.redirect('someurl'); } // Otherwise move on to the next middleware next(); } 

要么:

 function myFn( req, res, next) { var options = { // Fill this in with your needed options }; // Redirect if something has happened if (something) { res.redirect('someurl'); } // Otherwise render the page res.render('myPage', options); }