Node.js Unable to set headers after sending them. When initiating an XHR request within another XHR request

Node.js cannot process my client code that runs something similar to the jQuery / Zepto XHR template below:

$.ajax({ type: 'POST', url: '/someUrl', success: function(response) { $.ajax({ // ... do another XHR 

I did this (initiating an XHR request in another XHR request) earlier in a different framework. I read about Node.js Error: it is not possible to set headers after they are sent and how the event-based Node.js server model works. In other words, the first XHR request did not call res.end (), therefore, when the second XHR request is called Node. js complains (in btw continuous loop).

My questions is: can anyone recommend an alternative template for binding client-side XHR requests? Is there something I can do Node.js on the server side to keep the existing template on the client side?

Update based on accepted answer
The error is definitely in my own server side code. A simple check function was an error, but only res.end () was called after it was detected. For some reason, the assumption I had called res.end () immediately stopped the execution of the function. In this case, the insert "return" stops execution immediately after sending the JSON message to the client.

 if (_.isEmpty(req.body)) { res.end(JSON.stringify({'Error':'POST required'})); // suppose 'return' is needed here as well return } else { try { if (_.has(req.body, 'id')) { id = parseInt(req.body['id']); } else { throw {'Error':'Missing param in req.body'}; } // end if } catch(err) { res.end(JSON.stringify({'Error':'Missing key(s)','Keys':_.keys(req.body)})); // without a return here, the code below this 'do some more work' would // be executed return } // end else // do some more work // without the above 'return' the code would // a) make a database call // b) call res.end() again!!! <-- bad. 
0
jquery zepto
Feb 17 '12 at 17:22
source share
1 answer

The problem is not what you think. Your two XHRs are happening in serial, not parallel, due to callbacks. The success callback of the first will not work until the entire request / response has been completed for the first request (node.js has already called response.end () and the browser has received and parsed the response), Only then does the second XHR begin. You have a client side AJAX sample. It will work equally well with node.js and any other web server.

Your problem is in server.node.js server code on the server side, but this is not a bug or a restriction in node, this is a programming error on your part. Submit your server-side code and we can help you track it. Very often for beginners, node.js will hit this error with simple coding.

0
Feb 18 2018-12-18T00:
source share



All Articles