Ad

Using Node JS To Retrieve Twitter From User Input From Browser

- 1 answer

I'm new to using nodeJS and npm modules.

Using the module twit, I can do a GET request to the Twitter API and search tweets.

var Twit = require('twit')

var T = new Twit({ `login details`})

T.get('search/tweets', { q: 'banana since:2011-07-11', count: 100 }, function(err, data, response) {
  console.log(data)
})

I am trying to build a simple user browser page, where a user can enter their own query parameters. I understand that modules are server side, and we can't use them on the browser. I also can't use browserify because twitter uses Oauth method which means you can't access it from the browser.

Is there a way to pass query parameters from the browser back to the server code, and then to pass that result back to the browser?

T.get('search/tweets', { q: {user options}, function(err, data, response) {
  console.log(data)
})

We can use socket.io for the streaming twitter data, but how can I use it for the REST API?

Ad

Answer

Nodejs

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const Twit = require('twit');

...
const T = new Twit(LOGIN_DETAILS);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/search', function (req, res, next) {
  T.get('search/tweets', {q: req.body.searchQuery, count: 100}, function (err, data, response) {
    return res.json({
      data: data
    });
  });
});

Client Side

...    
$.ajax({
  url: "{API_URL}/search",
  type: "POST",
  dataType: 'json',
  data: JSON.stringify({
    searchQuery: SearchQuery
  }),
  contentType: "application/json; charset=utf-8",
  success: function (msg) {
    console.log(msg);
    // do something with the response
  }
});   

$ is jQuery, read more about jquery ajax

Ad
source: stackoverflow.com
Ad