Request.on ("response", [...]) never starts

I am currently working with NodeJS and am trying to use the Twitter-Search API. It works fine with curl - so there is nothing wrong with my firewall or something else. However, I never get a response in NodeJS.

 var sys = require("sys"), http = require("http"), events = require("events"); sys.puts("Hi there… "); var client = http.createClient(80, "search.twitter.com"), body = "", query = "foobar"; function getResults() { sys.puts("fetching for "+query); var request = client.request("GET", "/search.json?q="+query); request.on("response", function(data){ /* this somehow never gets fired :( */ sys.puts("BODY:"+ data); }); } var interval = setInterval(getResults, 5000); 

And the url also works .

Any hints or solutions are welcome!

Thanks in advance.

+4
source share
1 answer

You never send a request.

You need to use request.end()

NOTE: the request is not completed. This method sends only the request header. You need to call request.end () to complete the request and get a response. (This sounds confusing, but it allows the user to pass the body to the server using request.write ().)

Also, the response event parameter is the body of the response object NOT . You need to set the data event to a response object , and then listen to the end event to make sure you get all the data.

 request.on('response', function (response) { var body = ''; response.on('data', function (chunk) { body += chunk; }); response.on('end', function () { console.log('BODY: ' + body); }); }); request.end(); // start the request 

See: http://nodejs.org/api/http.html#http_class_http_clientrequest

Some tips

  • You might want to use querystring.escape to url your search parameter
  • You also need to set the Host header, otherwise Twitter will return 404

Fixed Code:

 var querystring = require('querystring'); ... var request = client.request("GET", "/search.json?q=" + querystring.escape(query), {'Host': 'search.twitter.com'}); 
+8
source

All Articles