Reputation: 2269
I'm using mongoosastic and it's working fine but the problem that I'm facing is that, how do I take the object from .post
method and pass it to .get
method?
For example:
router.post('/search', function(req, res, next) {
Product.search({ something: 'Something'}, function(err, result) {
if (err) return next(err);
res.redirect('/search') // <--- How do i pass the result object?
});
});
router.get('/search', function(req, res, next) {
res.render('search');
});
I tried another approached where I use req.flash
, but I don't really like that approach.
How did you guys solve this problem? it's a really basic search, where user search then it will redirect that user to another page where it either will show the found result or not found.
Upvotes: 1
Views: 10562
Reputation: 7803
You don't need to redirect the user to another route with GET to send the response.
You can serve the request in .post
and it is perfectly acceptable.
POST
and GET
are two forms of HTTP Request. No matter what type of request comes to a web server, the response could be anything. It could be a redirect, or an actual web-page, or other types of things such as errors.
I don't think you need this, but just to be complete, for search pages it could be a different scenario. GET requests could be bookmarked in the browser, because all it takes to re-render the page is the URL. But POST requests could not be, because it needs post parameters as well which is in the request's body. If you want to let the users bookmark the page with the result or have a permanent link to the same page with the result, you could serve the request in GET requests (as well). Adding an extra parameter like ?q=search-term
to the URL for example ...
This is a sort of sending parameters via GET request. A /search
route will also catch a /search?q=search-term
URL. You can have access to that using req.query.q
and its value would be "search-term"
(look at this question for more info). So you can either modify your form to send a GET request instead of POST (<form action="get">...
) or you can redirect the user back to the search page using GET and pass the parameter along the URL. And finally serve all the search result in a GET request.
But again, this is more advanced stuff, for what you need to do, generally, it is all good to serve a request whether it is POST or GET or anything else.
Upvotes: 4