To access the Twitter API, do not try to use it from the browser directly through browserfy or similar, since you should expose your keys, which are secret. This discouraged by them .
Create a server application that consults the API and exposes an access point to "bridge" your server that actually makes the query, so that your keys are not compromised.
// server.js
var express = require('express');
var Twitter = require('twitter');
var twclient = new Twitter({
consumer_key: '', // debes poner los datos correctos en estos campos
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
});
// creamos la applicacion con express
var app = express();
// configuramos la carpeta 'public' como una carpeta de contenido estatico, html, css, etc.
app.use(express.static('public'));
app.get('/ultimotweet/:user', function(req, res){
// preparamos los datos del usuario a consultar
var usuario = {
// en screen_name, pones el nombre de usuario sin la arroba.
// req.params.user, el valor que viene en la solicitud ej: /ultimotweet/nombreuser => nombreuser
screen_name: req.params.user,
// la cantidad de mensajes a obtener
count: 1,
// solo mensajes propios (no re-tweets)
include_rts: false
};
twclient.get('statuses/user_timeline', usuario, function(error, tweets, response){
if(error) throw error; // se produjo un error, manejar aquí
if (tweets.length) {
// como hay tweets, con res.send enviamos la respuesta al navedador.
res.send(tweets[0].text);
} else {
// como no hay tweets mandamos un mensaje que lo explique.
res.send('El usuario no ha twiteado aun!');
}
});
});
app.listen(3000);
Then make a client application similar to this one:
Using ajax, query the access point created in the previous application and you get the information you are looking for.
<input id="user" type="text" placeholder="ingresa el usario de sin la @">
<button id="pedir">Obtener</button>
<div id="destino_tweet">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#pedir').click(function() {
$.ajax({
url: '/ultimotweet/' + $('#user').val()
}).done(function( data ) {
$('#destino_tweet').text(data);
});
});
});
</script>
Leave a repository on GitHub so you can try this concept, with instructions so you can execute it.
link