I want use Twitter API (https://www.npmjs.com/package/twitter) and here are the thinks I'd like to add:
app.js & package.json
var express = require("express"),
path = require("path"),
http = require("http"),
twitter = require("twitter"),
app = express();
http.createServer(app).listen(3000);
twitter_data.js
var Twitter = require('twitter');
var client = new Twitter({
consumer_key: '',
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
});
var params = {screen_name: 'nodejs'};
client.get('statuses/user_timeline', params, function(error, tweets, response){
if (!error) {
console.log(tweets);
}
});
I'll try to keep it short, here we go:
Install express-generator module first: npm install -g express-generator
Run express --hbs
(you can choose Jade or anything else, but I prefer Handlebars, so I'll continue with that)
Go to the folder and install dependencies: npm install
Install twitter module: npm install --save twitter
Go to Twitter's Application Management Page and create your app. Get the necessary keys: consumer_key, consumer_secret, access_token_key, and access_token_secret.
After this point, I'd like to share the actual codes instead of explaining what to do
Here's /routes/index.js file:
var express = require('express');
var Twitter = require('twitter');
var router = express.Router();
var client = new Twitter({
consumer_key: 'XXX',
consumer_secret: 'XXX',
access_token_key: 'XXX',
access_token_secret: 'XXX'
});
router.get('/', function(req, res, next) {
// https://dev.twitter.com/rest/reference/get/statuses/user_timeline
client.get('statuses/user_timeline', { screen_name: 'nodejs', count: 20 }, function(error, tweets, response) {
if (!error) {
res.status(200).render('index', { title: 'Express', tweets: tweets });
}
else {
res.status(500).json({ error: error });
}
});
});
module.exports = router;
And here's /views/index.hbs file:
<ul>
{{#each tweets }}
<li>{{ this.text }}</li>
{{/each }}
</ul>
When you save them all and run npm start
, you can see the results at http://localhost:3000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With