How to perform Twitter API search in Node.js with user-entered keyword How to perform Twitter API search in Node.js with user-entered keyword express express

How to perform Twitter API search in Node.js with user-entered keyword


You need to think about where each step is happening. The Twitter code you're showing is running in Node, on your server. The myCtrl code is AngularJS code, running in the browser. As you've sensed, there's something missing to connect them.

The flow of control will be like this:

  • user types in a term and clicks the Search button
  • your controller sends an HTTP request to your Node.js
  • your Node.js server makes a call to Twitter
  • Node.js hands the results back to the client (myCtrl)
  • the results are displayed to your user

You have pieces of this in place. What's missing is the HTTP request and response. Here's what you do:

  • add an endpoint, say, /api/twittersearch. You'll do this with Node.js and Express
  • the implementation of that endpoint will be a function with parameters req and res (request and response; those names are not required but are frequently used); this function will do the new Twitter and client.get code that you have above
  • the client.get call has a callback function, which you have currently implemented; in your callback, you'll send the tweets back to the client (something like res.send(tweets)
  • in your controller, your "search here" code will be something like $http.get('/api/twittersearch?term=' + searchTerm)

That last call to $http.get() returns a Promise. You'll follow that up with .then(function(tweets){ ... }).catch(function(errors){ ... }). In the function you pass to then, you'll take the results from your call and update your model.