I am a newbie to node.js but I am getting a “write after end” error and I am not sure why. I know there are other similar questions but none of them provide a working solution to my problem I am trying to query the twitter api.
req.on('end', function() {
var string = JSON.parse(body);
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(body);
var tweetsArray = [];
var finalTweets = [];
client.get('search/tweets', {
q: string.teamname,
count: 1
},
function searchTweets(err, data, listStatuses) {
for (var index in data.statuses) {
var tweet = data.statuses[index];
tweetsArray.push(JSON.stringify(tweet.text));
}
/* Callback function to query Twitter for statuses*/
client.get('statuses/user_timeline', {
screen_name: string.teamname,
count: 1
},
function listStatuses(err, data, response) {
for (var index in data) {
var tweet = data[index];
tweetsArray.push(JSON.stringify(tweet.text));
}
var tweets = JSON.parse(tweetsArray[0]);
var tweetsB = JSON.parse(tweetsArray[1]);
finalTweets = tweets.concat(tweetsB);
res.write(JSON.stringify(finalTweets));
res.end();
});
});
2
Answers
You call
res.end(body);
before even invokingclient.get('search/tweets'
. Then you haveres.write(JSON.stringify(finalTweets));
(and alsores.end()
again). You can’t close the http response and then write to it.You are calling
res.end()
near the beginning of your router. This ends the response, and then once your callback is executed you are writing to the response again withres.write(JSON.stringify(finalTweets));
.