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


Question

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)

1
36
2/23/2015 2:29:13 PM

Accepted Answer

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.

48
9/27/2017 7:30:33 AM

For future reference, you can also do:

res.redirect('back');

Basically this just redirects the browser back to the screen the request came from, in other words "refreshing" it. It's hacky and I wish there was a better way, but it works.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon