http请求中的Nodejs回调函数

时间:2017-04-12 09:18:11

标签: javascript node.js https callback

我收到错误,找不到功能。 我不明白..是不是因为https.get中的回调? 我想在http请求完成后调用回调函数。

    const happy = ['happy'];
    twitterService.twitter(happy, '1233,1233', '50', function (length) {
        console.log(length + "  bepedie boopdap");
     });

twitter.js

module.exports.twitter = function (hashtags, location, distance, callbackLength) {

    if (hashtags.length !== 0) {
        let hashURL = createHashtagUrl(hashtags);

        const options = {
            host: config.apiURL,
            path: '/1.1/search/tweets.json?q=' + hashURL + '&geocode=' + location + ',' + distance + 'km&count=100',
            method: 'GET',
            headers: {
                'Authorization': 'Bearer ' + config.base64Token
            }
        };

        https.get(options, function (res) {
            let body = '';

            res.on('data', function (data) {
                body += data;
            });

            res.on('end', function () {
                let jsonObj = JSON.parse(body);
                let length = jsonObj.statuses.length;
                callbackLength(length); // HERE its says .. is not a function

            })
                .on('error', function (e) {
                    console.log("ERROR BEEP BEEP" + e);
                });
        });
    }
};

function createHashtagUrl(hashtags) {

    let hashURL = config.hashtagUnicode + hashtags[0];

    for (let i = 1; i < hashtags.length; i++)
        hashURL += '+OR+' + config.hashtagUnicode + hashtags[i];

    return hashURL;
}

有人有想法吗?

1 个答案:

答案 0 :(得分:0)

不确定,但可能需要更改请求部分。

  var req = https.get(options, function (res) {
        let body = '';

        res.on('data', function (data) {
            body += data;
        });         
    });

 req.on('end', function () {
                let jsonObj = JSON.parse(body);
                let length = jsonObj.statuses.length;
                callbackLength(length);
            })
                .on('error', function (e) {
                    console.log("ERROR BEEP BEEP" + e);
                });`enter code here`