简体   繁体   中英

Nodejs twitter api 403

I am trying to use the twitter api with nodejs 5.4.1, using the twitter api as a guide . Initially my bearer access token appears to be generated properly, though when I run the actuall request I keep getting a '403 Forbidden' error message. Any idea why this is?

var R = require("request");
var stream = require('twitter');
var https = require('https');


var key = 'my-key';
var secret = 'my-secret';
var cat = key +":"+secret;
var credentials = new Buffer(cat).toString('base64');

var url = 'https://api.twitter.com/oauth2/token';

R({ url: url,
    method:'POST',
    headers: {
        "Authorization": "Basic " + credentials,
        "Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"
    },
    body: "grant_type=client_credentials"

}, function(err, resp, body) {

    var an = JSON.parse(body);
   console.log( an['access_token']);

   runIt(an['access_token']);
    console.dir(body); //the bearer token...

});



function runIt(key){

var options = {
host: 'api.twitter.com',
path: '/1.1/users/search.json?q=Twitter%20API&page=1&count=3',
headers: {
        'Host': 'api.twitter.com',
        'Authorization' : 'Bearer ' + key,
        'Accept-Encoding': 'gzip'
}
};

https.get(options,(res)=>{
        console.log(res.statusCode);
        console.log(res);
});

}

For Twitter User Api you'll have to follow the proper oauth steps to get things work properly.

Initialy there will be 2-step request process that will leave you with token and secret of user.

You will use that information to sign request with method like HMAC-SHA1 so that you can access data from twitter, node-auth can be helpful in this step. Twitter Link - Authorizing requests

For further understanding see these tutorials:

and for code inspiration:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM