Reputation: 385
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();
});
});
Upvotes: 2
Views: 150
Reputation:
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 with res.write(JSON.stringify(finalTweets));
.
response.end([data][, encoding][, callback])
This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.
Upvotes: 2
Reputation: 4363
You call res.end(body);
before even invoking client.get('search/tweets'
. Then you have res.write(JSON.stringify(finalTweets));
(and also res.end()
again). You can't close the http response and then write to it.
Upvotes: 0