Reputation: 5
I'm following along a exercise on Pluralsight and it basically amounts to sending a get request with a query for a Twitter user's last 10 tweets and displaying the data.
On the Twitter Dev portal I've created my app and generated my projects tokens. However for the life of me I cannot find out how to send the token with the GET request so that I may access the API (otherwise you can't)
I've searched here and Google and only found how to generate the tokens. Some help would be much appreciated.
var express = require('express');
var request = require('request');
var url = require('url');
var app = express();
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get('/tweets/:username', function(res, req){
var username = req.params.username;
options = {
protocol: 'http:',
host: 'api.twitter.com',
pathname: '/1/statuses/user_timeline.json',
query: { screen_name: username, count: 10},
}
var twitterURL = url.format(options);
request(twitterURL).pipe(response);
});
app.listen(8080);
Edit
So the reason this didn't work is because of two separate issues. One the Twitter API has changed over the last few years and code examples such as the one below no longer follows the Twitter api standard. I would instead recommend using a pre-written module such as the one here; https://github.com/desmondmorris/node-twitter
The second issue is that when I signed up I didn't use a real callback website. I was developing locally and honestly didn't think it was going to matter. Well turns out it does.
The code I ended on;
// Imports
var express = require('express');
var request = require('request');
var url = require('url');
var twitter = require('twitter');
var config = require(__dirname + '/conf/config.js');
// Variables
//var twit = twitter(config);
var app = express();
var twit = new twitter({
consumer_key: '',
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
});
// Routes
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get('/tweets/:username', function(req, response){
var username = req.params.username;
var params = {
screen_name: username,
count: 10
}
twit.get('statuses/user_timeline', params, function(err, tweets, res){
if(!err){
console.log(tweets);
}
else{
console.log(err);
}
});
});
app.listen(8080);
Upvotes: 0
Views: 25
Reputation: 2528
Try
var express = require('express');
var request = require('request');
var url = require('url');
var app = express();
app.get('/tweets/:username', function(req, res){
var username = req.params.username;
options = {
protocol: 'http:',
host: 'api.twitter.com',
pathname: '/1/statuses/user_timeline.json',
query: { screen_name: username, count: 10},
}
var twitterURL = url.format(options);
request(twitterURL).pipe(response=>res.send(response));//send response
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.listen(8080);
Upvotes: 1