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.
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.
Related
I am trying to display a page after a get request received. For example, some user send a get request to my server, ('/home') and I want to display home page after that.
I tried res.render but it doesn't change the page. It only send url back.
fetch('lom').then((res)=>{
console.log(res);
}); //GET Request
app.get('/lom',(req,res)=>{
res.render('lom');
}); // Respond
I expect to see /home page after request but current page is not changing.
I don't want to use window.location.href = '/lom'. I want to change page in server side.
You're using fetch.
The entire point of using fetch is that the browser doesn't navigate to a new page, and the response is processed using JavaScript instead.
Use a regular link. Submit a form. Use window.location.href = '/lom' (I know you said you didn't want to, but not wanting to do the right thing is a terrible reason not to do it). But do something which causes the browser to navigate. fetch is the wrong tool for the job.
I want to change page in server-side.
There is no way to trigger navigation in the browser directly from the server-side. There needs to be something on the client designed to navigate (this might be triggered by client-side code based on data in a response from the server, but it still needs to be client-side).
I'm not sure if I fully undestand your problem, at any rate, take a look at below code, a res.send command sending content to be displayed (https://expressjs.com/en/guide/routing.html).
app.get('/', function (req, res) {
res.send('root')
})
I'd recommend to interest in a template engines
https://expressjs.com/en/advanced/developing-template-engines.html
Fetch is going to do only XMLHttpRequest request to 'lom' (ajax call), which not supposed to redirect your page but to receive just the response in your res parameter.
fetch('/lom').then((res)=>{
console.log(res);
}); //GET Request
So you will see your response in your browser console tab by doing console.log. Anyway if you want to do a redirection do it in the client side, for ex: window.location = '/home'.
Long time, first time. I am new to learning node JS, Javascript, express, etc. and have been dealing with a problem for three days and counting. Hoping for some kind help here.
I have a view (called 'standings' view) where the user fills in an HTML form entering their username and bunch of team names.
I handle the post request using express and save the data in mongodb
The request contains a username field which can be referenced by 'req.body.username' inside the express app.post method.
What I am trying to do is capture this 'req.body.username' from the POST request and use it in another JS file (called 'thankyou.js') which would be the config file for a "thankyou" view. In other words, I am looking for a way to somehow reference the 'req.body.username' parameter directly without having to go back to the DB and in my "thankyou" view I want to say something like:
"Thank you" + <%= req.body.username %> + "for contacting us".
What would be the best approach to accomplish this? I have thought of and researched the following but not quite sure how to implement:
Somehow export 'req.body.username' property in my standings JS file and require/reference it in the thankyou JS file.
Using query strings to pass the 'req.body.username' in standings.js to the thankyou view.
Here is my express app.post method which handles the POST call from the user for the 'standings' view:
app.post('/standings', urlencodedParser, function(req, res){
var newStandings = standingsModel.update({ username: req.body.username}, req.body, {upsert: true}, function(err,data){
if (err) throw err;
res.json(data);
})
});
Thanks in advance.
Are these REST calls? It looks like it, so I'm going to assume that this is stateless and you can't use session, right?
When do you send the user to the "thank you" page? If it's after submission, can you do a redirect instead of making everything an AJAX call?
I would take a look at this answer on passing data between routes/pages in ExpressJS. See if that offers any value to you. You might have to make some architectural changes.
The scenario is to save the data in cache. We have numerous express routes written with complicated logic.
I have to find a way to save the response data in cache. I cannot go to each and every route and check whether this needs to be saved and save the data before sending the response. (If no other go, then this may be the way)
I have tried the following approaches.
https://nodejs.org/api/http.html#http_event_close_1 - using 'close' or 'finish', which fires after sending the response would do the trick. But there is no way I could get the response data in these events.
Also my node version is v0.10.31
Thought of using app.all('*', callback), but i am not sure how to catch the response data for cacheing.
Finally i thought of adding a second callback for routing, app.VERB(path, [callback...], callback), but upon returning the response in first callback, second callback is never called.
Hoping there is a solution for this, and I am stuck in this for more than a week.
The reason why adding logic into each and every routes is a tedious job is that, I need to add a configuration entry specifying which route needs to be cached with an expiry time.
Response needs to be cached in redis server. A cache key will be generated based on the route data and query strings. All those complete user specific information will be saved in a key.
So when the user hits the same route the key will be generated to check if it already exists using app.use and the data will be served without precedding to the successive middlewares.
Define a callback middleware as,
var storeResponseMiddleware = function(req, res, next) {
console.log("storing data in redis....")
..........more stuff
}
Add it to expressJs app as,
app.use(logicRoute)
app.use(storeResponseMiddleware)
Now, for all the responses storeResponseMiddleware will be called. you must call next() inside the route handlers.
I am developing an express application in which I need to render a landing page for '/' route. This page has a text box and a button. When user adds text to textbox and hits submit button I need to make request to same url but with text added as its query parameter. This request will render a new page whose contents depend upon query text.
Now what is happening is when user enters text into textbox and presses button, form makes GET request and route looks something like http://localhost:3000/?q=abc. I can see this request as pending in network tab of chrome developer tools but this request never reaches server. I cannot see any request for /?q=abc in server console.
If I restart server and then open http://localhost:3000/?q=abc, proper contents get loaded in browser. But if I change url back to http://localhost:3000, I can see pending request in network tab and this request never reaches server.
My code looks something like:
app.get('/', function(req, res, next) {
if(req.query.q)
res.render('results.ejs');
else
res.render('landing.ejs')
});
Any idea why no call to server is being made? I have spent whole day trying to figure out reason for this behavior. Any help will be greatly appreciated.
Have you tried inserting temporary middleware to see where exactly the request gets stuck in your middleware/route chain? It sounds like there is a middleware somewhere that is not calling next() in some situation.
Through several threads I can see that the use of the MVC antiforgery token is overkill on areas of a site where a user is not authenticated.
I have an application that posts some information to mysite.com from site1, site2, site3, etc. Each site has a unique identifier that gets sent in the POST request through an asynchronous Javascript POST. The Javascript that is executed on site1-3, is generated on mysite.com, then returned to the sites with some Javascript variables populated.
So the lifecycle is as follows:
A page on site1 has a Javascript reference to mysite.com.
That link reference is to a controller route that generates Javascript to return to site1.
The end of the JS that is returned contains a POST request that goes back to mysite.com containing Url, browser, etc., details for the visitor of the page on site1.
I can read in the POST parameters just fine in the accepting controller from the JS POST request, however, what I wanted to know is if there is any point in adding an antiforgery token to the parameter list.
If so, I would have to generate it on the initial request, and pass it back as a JS variable in the JS returned to site1, then pass it back along with the form POST in the second request.
Since any processing on mysite.com will only occur if a valid account is found, is there any point in going through this?
If so, how would I generate the antiforgery token on at the controller level?
I would say that it depends on the sensitivity of the data that is being posted. If another user could cause harm (or annoyance) by crafting forged requests and submitting them, then I would say that it would be appropriate. It sounds like you're just collecting some usage information so that's not likely to be the case.
A one-time, random nonce might be a better solution. That would make it difficult to forge a request and prevent erroneous multiple submits, say from the user using a cached copy. Generate a random value (a GUID might work) on mysite.com, inserting it in the database and marking it as unused. Send it back with the POST. Check whether it has been used or not. If not used, then mark it used and perform your logging action. If it has been used already, discard the request as a duplicate submission.
Note that you wouldn't need a POST for this, a simple GET with URL parameters would be sufficient since the nonce will prevent it from being accidentally repeated.