Wednesday, 7 June 2017

Sending a variable from server to client with Node.js

I'm getting the API information I need on my Node.js server, but I now need to manipulate it on the client side. I haven't worked with servers in a long time and none of the SO questions I've found have given the solution I need.

I need to send markovStrings to the client as the array of strings I created in my function. I've read about passing the array through the .pug file, but given the potential size of the array, that feels like bad practice.

I haven't included any code from the client side javascript because nothing is written to gather server information (which I'm sure is part of the problem I can't solve), but I do know my routes are correct for it because test button in my .pug file triggers its corresponding client side function.

server.js (relevant snippets)

var T = new Twit(config);
var markovStrings = [];    
var twitterHandle = 'twitterHandleHere';
var params = {
    screen_name: twitterHandle,
    count: 5
}

app.set('view engine', 'pug');

app.get('/', function(req, res) {
    res.render('index', {
        twitterHandle: twitterHandle,
        allTweets: T.get('statuses/user_timeline', params, gotUserTweets)
    })
    res.sendFile(__dirname + '/views/index.html');
});

// GET REQUEST //
T.get('statuses/user_timeline', params, gotUserTweets);

// FUNCTION //
function gotUserTweets(err, data, response) {
    // put all tweets into array
    for (var i = 0; i < data.length; i++) {
        var removeMentionsAndLinks = data[i].text.replace(regexMess)
        var trimmedTweet = removeMentionsAndLinks.trim();

        if (trimmedTweet != '') {
            markovStrings.push(trimmedTweet);
        }
    }
    console.log('INSIDE FUNCTION:: ',markovStrings);
    return markovStrings;
};
console.log("OUTSIDE FUNCTION:: "+markovStrings);

currently, this final console.log returns nothing and I can't figure out why.

index.pug

body
    p Twitter Handle: #{twitterHandle}
    p #{allTweets}

    button#testButton Click Me

    // APPLICATION SCRIPTS
    script(src='/static/js/script.js')

currently, p #{allTweets} is rendered as "[object Promise]"



via Rokitar

No comments:

Post a Comment