Search code examples
node.jstwittertwitter-oauth

Twitter stream API with node.js ERROR status code 401 at request: <anonymous>


i'm very new to Twitter Streaming API and Node.js (i just learned both yesterday). I'm trying to create a basic program like this https://www.youtube.com/watch?v=5b98CC9IvZ8 that streams tweets from twitter. I followed every step but i get this error:

C:\Program Files\thesis>node twitter_collect.js
events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: Status Code: 401
    at Request.<anonymous> (C:\Program 
Files\thesis\node_modules\twitter\lib\twitter.js:277:28)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at Request.onRequestResponse (C:\Program 
Files\thesis\node_modules\request\request.js:1074:10)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] 
(_http_client.js:473:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
    at TLSSocket.socketOnData (_http_client.js:362:20)
    at emitOne (events.js:96:13)

Below is my code:

var twit = require('twitter'),
twitter = new twit({
    consumer_key: 'Q7IcJHDBxWtmlqSj0JgublbaJ',
    consumer_secret: 'ylnM1Cfed4WMLO0VCUoIZxoLt77LTNEiqQ1h1LAtWWdfWVM2sh',
    access_token: '838296902739189760-E8ZMEDA6EYLrryIOEcx2Ud5CIZiBhJQ',
    access_token_secret: 'qqLAa11ysBpl4tZauPzrsITmLdJWYHr22DwGKmCkN2MI5'
});

var count = 0,
util = require('util');

twitter.stream('filter', {track: 'love'}, function(stream){

    stream.on('data', function(data){
        console.log(util.inspect(data));
        stream.destroy();
        process.exit(0);
    });
});

Solution

  • I found the solution.

    The Access Token has a prefix, e.g. "44553093-DEfu2ftEiHfRopZsL0YXmTSrOHDuhgyZNzrSW8LqY". You are missing the prefix i.e. "44553093". I was doing the same mistake.

    The UI of that page is not ideal, since the token is split in two lines and it is easy to miss the first line containing the prefix. See the image below.

    enter image description here