Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end an express.js / node POST response?

Im trying to just stop the post request after I've saved a document to the DB, ie:

app.post('/blah'), function(req,res){  //my code does a bunch of stuff  res.what do i put here to tell the client browser to just... stop the POST } 

At the moment im simply using res.redirect('back') which works, but the page refresh is totally arbitrary and i would prefer it didnt happen. I had a go at res.end(); but that sends the client to a blank page...

Thanks in advance.

edit:

I dont think i made myself clear enough in what im doing sorry.

Perhaps its bad practice but this is whats happening:

  1. POST initiates database save function

  2. Browser sits around waiting for a response

  3. When its good and ready, the obj is saved to the DB, then a callback triggers a NowJS function, which adds the item to the view(for everyone)

I did it this way to be non-blocking( so i thought)

like image 786
Andrew Plummer Avatar asked Feb 02 '12 04:02

Andrew Plummer


People also ask

How do you end a response in node JS?

end() function is used to end the response process. This method actually comes from the Node core, specifically the response.

What is POST () in Express?

js POST Method. Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.

How do I cancel a node js request?

Update: If you're using Node. js >= v16. 14.0 and want to cancel an HTTP request after a specific amount of time, I'd recommend using the AbortSignal. timeout() method.

Is Express JS back end?

js, or simply Express, is a back end web application framework for Node. js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs.


1 Answers

You can use res.end and pass in a string that you want to be sent to the client:

res.end('It worked!'); 

Alternatively, you could render a view and then end the response:

res.render('blah.jade'); res.end(); 

All that said, redirecting the client is actually the best practice. It makes it so that when they hit the back button in their browser, they can move back seamlessly without getting any "POST required" popups or the like. This is the POST/redirect pattern and you can read more about it at http://en.wikipedia.org/wiki/Post/Redirect/Get.

like image 185
Rohan Singh Avatar answered Sep 29 '22 03:09

Rohan Singh