Access req in expressjs 3 expressions

Can I access my query parameters in my views in ExpressJS 3?

I have url: http://example.com?search=blah

And, in my opinion, I would like to access the search parameter

I can convey this as local residents, but I wonder if I can access it directly - my experiments were not successful.

Do not look for the pros and cons of direct access - you just want to find out if this is possible and how.

0
source share
3 answers

Here are some ways to access req.query from your view:

Set it as local in the render call

 function(req, res) { res.render('myview', {query: req.query}); }; 

in your view, you can access search as query.search .

Install res.locals

 function(req, res) { res.locals.query = req.query; res.render('myview'); }; 

in your view, you can access search as query.search .

Use middleware

This is similar to the previous example, but we can use the middleware in reusable mode.

 function(req, res, next) { res.locals.query = req.query; next(); }; 

Any route that uses the above middleware will have res.locals.query .


change

It seems I did not understand this question. The goal was to see if it was possible to access the query data without using the above methods. As far as I know, this is not possible. We hope that the above will continue to be useful to some readers.

+2
source

I am sure that only local residents are transferred to the submission.

Do not look for the pros and cons of direct access - you just want to find out if this is possible and how.

There are no pluses or minuses. I like to say that I want to multiply 15 by 0, but I do not want the answer to be an apple.

+1
source

middle layer:

 function(req, res, next) { res.locals.param = req.param; next(); }; 

View:

 <%= param.search %> 
+1
source

All Articles