How to get req and res object of Expreejs in .ejs file

user1481951 picture user1481951 · Jan 17, 2013 · Viewed 10.2k times · Source

I am trying to use Express js with .ejs views.

I want to redirect my page to some another page on any event let say "onCancelEvent"

As per Express js documentation,I can do this by using res.redirect("/home");

But I am not able to get res object in my ejs file.

Can anyone Please tell me how to access req and res object in .ejs file

Please help.

Thanks

Answer

Weihong Diao picture Weihong Diao · Jan 17, 2013

Short Answer

If you want to access the "req/res" in the EJS templates, you can either pass the req/res object to the res.render() in your controller function (the middleware specific for this request):

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

Or set the res.locals in some middleware serving all the requests (including this one):

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

Then you will be able to access the "req/res" in EJS:

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

Further Discussion

However, do you really want to use res in the view template to redirect?

If the event initiates some request to the server side, it should go through the controller before the view. So you must be able to detect the condition and send redirect within the controller.

If the event only occurs at client side (browser side) without sending request to server, the redirect can be done by the client side javascript:

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