Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 499
user1481951 Avatar asked Jan 17 '13 07:01

user1481951


1 Answers

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";
like image 123
Weihong Diao Avatar answered Sep 30 '22 19:09

Weihong Diao