angularjs - Node js, TCP request from front-end causing crash -


i creating website involves user pressing button performs http request node server. there, node server opens tcp socket using "net.socket()". afterwards, send response after message delivered using res.send("ok"). when user presses multiple times error below. also, when server communication tcp not available, same issue occurs well. there way can prevent multiple requests user or when tcp server not available crashing node server?

can't set headers after sent.         @ serverresponse.outgoingmessage.setheader (_http_outgoing.js:344:11)         @ serverresponse.header (/users/kevin/documents/mic/node_modules/express/lib/response.js:719:10)         @ serverresponse.send (/users/kevin/documents/mic/node_modules/express/lib/response.js:164:12)         @ serverresponse.json (/users/kevin/documents/mic/node_modules/express/lib/response.js:250:15)         @ serverresponse.send (/users/kevin/documents/mic/node_modules/express/lib/response.js:152:21)         @ /users/*****/documents/***/routes/***.js:275:15         @ socket.<anonymous> (/users/*****/documents/***/routes/***.js:829:5)         @ emitone (events.js:96:13)         @ socket.emit (events.js:188:7)         @ tcp._handle.close [as _onclose] (net.js:492:12) 

my function

  tcp_client_send('***.***.*.***', 3000, server, function(err, data){     if(err){       logger.log('error', err);       return next("err_msg");     }     else{       logger.log('info', 'successfully sent message.');       res.send("ok);     }   });  //tcp client send function tcp_client_send(ip, port, data, cb) {   var client = new net.socket();   var message;    client.connect(port, ip, function() {     client.write(json.stringify(data));     client.destroy();   });    client.on('data', function(data){     message = data.tostring();   });    client.on('close', function(){     cb(null, message);   });    client.on('error', function(err) {     client.destroy();     cb(err, null);   }); } 

your code call callback twice if error occurs:

client.on('close', function(){   cb(null, message); // <-- here });  client.on('error', function(err) {   client.destroy();   cb(err, null);     // <-- , here }); 

the fine manual states, error event:

emitted when error occurs. 'close' event called directly following event.

so both close , error handlers called, , both call callback.

you should check argument passed close handler, true when error had occurred. in case, don't call callback:

client.on('close', function(haderror) {   if (! haderror) cb(null, message); }); 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -