部署到heroku的问题

时间:2017-11-11 11:42:07

标签: javascript node.js heroku

所以这是我的基本Twitter机器人,它使用Node从@引用中查找搜索词,然后找到与之相关的GIF动画:

//Dependencies
const Twitter = require('twitter');
const http = require('http');
const config = require('./config.js');
const giphyApiKey = (process.env.apiKey || config.giphy.apiKey);
let searchString = "";
let giphyQueryUrl;

//Initialize twitter client
const client = new Twitter({
  consumer_key: (process.env.consumer_key || config.twitter.consumer_key),
  consumer_secret: (process.env.consumer_secret || config.twitter.consumer_secret),
  access_token_key: (process.env.access_token_key || config.twitter.access_token_key),
  access_token_secret: (process.env.access_token_secret || config.twitter.access_token_secret)
});

process.on('unhandledRejection', (reason,promise) => {
    console.log('Unhandled Rejection at:', promise, 'reason:', reason);
})

//This stream checks for statuses containing '@[USERNAME]' references, strips out the relevant seach data and feeds
//that search data to the queryGiphy function
client.stream('statuses/filter', {track: '@[USERNAME]'}, (stream) => {
    stream.on('data', (tweet) => {
        searchString  = 
            tweet.text.substring(tweet.text.indexOf("@[USERNAME]")+"@[USERNAME]".length + 1,tweet.text.length);
        giphyQueryUrl = "http://api.giphy.com/v1/gifs/search?q="+searchString+"&api_key="+ giphyApiKey +"&limit=5&rating=g";
        let replyString = '@' + tweet.user.screen_name + ' ';
        let giphyUrl = queryGiphy(replyString,giphyQueryUrl);
    })
})

//This function will query the Giphy API using the node http module and when it finds a match, posts that to twitter
//using the gifUrlToPost function
function queryGiphy(replyString,queryUrl) {
    http.get(queryUrl, res => {
        res.setEncoding("utf8");
        let body = '';
        res.on("data", data => {
            body += data;
        });
        res.on("end", () => {
            body = JSON.parse(body);
            if(postToTwitter(replyString + body.data[0].url)) {
                return true;
            } else {
                return false;
            }

        });
        res.on("error", error => {
            console.log("Error: " + error);
        })

    });

}

//This simply posts the url of the gif passed to it
function postToTwitter(body) {
    client.post('statuses/update', {status: body})
        .then(tweet => {
            return true;
        })
        .catch(error => {
            throw error;
        });

}

我的问题是,当我将其部署到heroku时,我不断收到超时错误,没有地方可以将$ PORT连接到heroku以动态分配端口。现在,我理解了这个的本质,我之前已经将小型Web服务器部署到heroku,并了解如何设置环境变量,以便它可以动态分配端口号,以便使用Twitter设置流并查询Giphy。但是我在代码中的哪个位置呢?我不明白,在这种情况下,在哪里做?

1 个答案:

答案 0 :(得分:0)

你有app.js文件或bin文件,如果你有

app.set('port',(process.env.PORT||5000));

app.listen(app.get('port'),function(){

})

或者您需要在根目录中创建一个Procfile并将代码推送到heroku git

您可以阅读本文以进一步澄清 https://devcenter.heroku.com/articles/procfile