简体   繁体   中英

HTTP Request in Node Js

I know how http request works and I know how to send and receive response. This is the sample code of http request.

var http = require('http');    
var options = {
host: 'www.nodejitsu.com',
path: '/',    
port: '1337',    
method: 'POST'
};

callback = function(response) {
 var str = ''
 response.on('data', function (chunk) {
 str += chunk;
});

  response.on('end', function () {
   console.log(str);
  });      

}

var req = http.request(options, callback);

req.write("hello world!");
req.end();

In my site everything working fine Server B send request to server A and server A response to server B. But, one time I face a problem when there is huge no of traffic on server A and it was unable to receive any request from server B which halt the whole process.

So is there is any error block in request to handle this type of errors ? I googled alot and try this type of foolish things but it does not work for me

callback = function(response,error) {

 if(error){
   console.log(error)
 }else{
   var str = ''
   response.on('data', function (chunk) {
   str += chunk;
   });
   response.on('error', function (err) {
   console.log(err);
   }); 
 }
});

Have you tried this:

var req = http.request(options,callback);

req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

as given here: http://nodejs.org/api/http.html#http_http_request_options_callback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM