Reputation: 3843
I have this code:
app.post('/pst', function(req, res) {
var data = req.body.convo;
res.render('waiting.ejs'); //ADDED THIS
myFunc(data).then(result => {
res.render('success.ejs'); //THEN THIS
//---------------------------------
//clever way to send text file to client from the memory of the server
var fileContents = Buffer.from(result, 'ascii');
var readStream = new stream.PassThrough();
readStream.end(fileContents);
res.set('Content-disposition', 'attachment; filename=' + fileName);
res.set('Content-Type', 'text/plain');
readStream.pipe(res);
//--------------------------------------
}).catch( .....
What i want to do is when there is a POST, 1. grab the post information 2. do a res.render() 3. run a function with the post information as its parameters 4. do this code snippet that will allow the client to download stuff from the memory as a .txt file 5. do another res.render()
Everything works if we exclude the two res.render(). After i do one, i cannot set the headers. I get this error.
Error: Can't set headers after they are sent.
So i thought of a potential solution.
Is it possible that the app.post() will get the post data and do a res.render().
Then, return the post data, so another part of the code will handle calling the function with this data as parameter and then do the header manipulation thing, then finally do the last res.render().
Keep in mind this is the routes.js file.
Upvotes: 1
Views: 128
Reputation: 707326
HTTP is a request/response protocol. A client makes a request and gets one and only one response back. So, you can never call res.render()
twice on the same request.
Your problem is really defined by this desired sequence:
There are a number of ways to accomplish that:
Client uses Ajax instead of form post to send request
res.render()
window.location = xxxx
to change the current page to show new URL containing new contents.Form post response that uses webSocket/socket.io to get final results
All done via webSocket/socket.io
Upvotes: 2