我正在尝试创建一个应用程序,可以在一个页面中提供来自不同用户的推文。现在我只能使用下面的代码从一个用户生成推文?如果我想在一个页面中添加更多用户的推文,我该怎么办?
声明要求
var express = require("express"),
bodyParser = require('body-parser'),
errorHandler = require('errorhandler'),
Twitter = require('twitter'),
favicon = require('serve-favicon');
//Create the app
var app = express();
// Set up the views directory
app.set("views", __dirname + '/views');
// Set EJS as templating language, but allow for .html extension
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
//Add connection to public folder for css & js files
app.use(express.static(__dirname + '/public'));
app.use(favicon(__dirname + '/public/media/favicon.ico'));
app.use(bodyParser.json());
// Set up Express error handling
app.use(errorHandler());
// Start the server
var server = app.listen(3000);
console.log('Express started on port: ' + 3000);
var TWITTER_CONSUMER_KEY = 'xxx';
var TWITTER_CONSUMER_SECRET = 'xxx';
var TWITTER_ACCESS_TOKEN_KEY = 'xxx';
var TWITTER_ACCESS_SECRET = 'xxx';
var client = new Twitter({
consumer_key: TWITTER_CONSUMER_KEY,
consumer_secret: TWITTER_CONSUMER_SECRET,
access_token_key: TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: TWITTER_ACCESS_SECRET
});
/*--------------------------------------------
For this example, you need a twitter user's id
This site can help you with this
http://gettwitterid.com/
--------------------------------------------*/
var params = {
user_id: ('428333')
};
我想在我的应用中也包含此用户的推文。怎么做?我写的用户ID?
// var params1 = {
// user_id: ('27260086')
// };
//ROUTES
app.get("/", function(req, res){
res.render('index');
});
//Using the 'Twitter' lib - https://www.npmjs.com/package/twitter
app.get("/search", function(req, res){
client.get('statuses/user_timeline', params1, function(error, tweets, response){
if (error){
throw error;
}
console.log(tweets[0].text);
var theTweet = {'tweet': tweets[0].text };
res.json(theTweet);
});
});
app.get("*", function(req,res){
res.redirect("/");
});
我是节点新手。我是否需要在主javascript文件中执行某些操作?
答案 0 :(得分:0)
这应该对你有所帮助。虽然你需要做更好的错误处理,也可能需要格式化响应。
此外,您必须优化代码,因为我刚刚为用户粘贴了多次代码。我不会那样做,因为我很懒,你应该学会做那些事情。
var async = require("async");
app.get("/search", function (req, res)
{
async.parallel([
function ()
{
client.get('statuses/user_timeline', param1, function (error, tweets, response)
{
if (error)
{
throw error;
}
callback(null,tweets);
});
},
function ()
{
client.get('statuses/user_timeline', param2, function (error, tweets, response)
{
if (error)
{
throw error;
}
callback(null,tweets);
});
}],
function (err, results)
{
res.json(results);
});
});