2011-01-26 7 views
15

मैं वेबपृष्ठ डाउनलोड करने के लिए node.js का उपयोग कर रहा हूं। हालांकि, यह डेटा के किसी भी हिस्से को प्राप्त नहीं कर रहा है:node.js का उपयोग HTTP रिमोट क्लाइंट अनुरोध किसी भी शरीर को वापस नहीं करता

console.log('preparing request to ' + url) 
    u = require('url').parse(url) 
    var remote_client = http.createClient(80, u['host']); 
    var request = remote_client.request("GET", u['pathname'], {"host": u['host']}); 
    console.log("request made") 

    request.addListener('response', function (response) { 
     response.setEncoding('binary') 
     var body = ''; 

     response.addListener('data', function (chunk) { 
      body += chunk; 
      console.log('chunk received') 
     }); 
    }); 

अंतिम कंसोल संदेश "अनुरोध किया गया" है। "कंक प्राप्त" या पसंद के साथ कोई कंसोल संदेश नहीं हैं। विचार?

var sys = require('sys'), 
    http = require('http'); 

var connection = http.createClient(8080, 'localhost'), 
    request = connection.request('/'); 

connection.addListener('error', function(connectionException){ 
    sys.log(connectionException); 
}); 

request.addListener('response', function(response){ 
    var data = ''; 

    response.addListener('data', function(chunk){ 
     data += chunk; 
    }); 
    response.addListener('end', function(){ 
     // Do something with data. 
    }); 
}); 

request.end(); 
+1

आप http.get() http://nodejs.org/docs/v0.3.6/api/http.html#http.get – generalhenry

+0

आप भी स्विच कर सकता है भूल गया हाँ आप request.end() भूल जाते हैं, लेकिन मैं इस सादे पुस्तकालय के चारों ओर एक रैपर का उपयोग करता हूं। Https://github.com/ry/node/wiki/modules => देखें उदाहरण के लिए [अनुरोध] (http://github.com/mikeal/node-utils/tree/master/request/), [नोड-wwwdude ] (http://github.com/pfleidi/node-wwwdude) कुछ ही नाम देने के लिए। – generalhenry

+0

का उपयोग करने के request.end() – Alfred

उत्तर

12

यह एक उदाहरण है जो हमेशा मेरे लिए काम किया है। इसके अलावा आपको अपने अनुरोध में उपयोगकर्ता-एजेंट शीर्षलेख जोड़ना चाहिए। कई वेब सर्वर इसकी तलाश करते हैं।

console.log('preparing request to ' + url) 
u = require('url').parse(url) 
var remote_client = http.createClient(80, u['host']); 
var request = remote_client.request("GET", u['pathname'], {"host": u['host'], 
                  "user-agent": "node.js"}); 
console.log("request made") 

request.addListener('response', function (response) { 
    response.setEncoding('binary') 
    var body = ''; 

    response.addListener('data', function (chunk) { 
     body += chunk; 
     console.log('chunk received') 
    }); 
}); 

request.end(); 
+0

0.10 से http.createClient को हटा दिया गया – Advanced

1

आप() के अनुरोध पर अंत कॉल करने के लिए संकेत करने के लिए है कि आप इसे भेजने के लिए तैयार कर रहे हैं की जरूरत है:

संबंधित मुद्दे