How to call Twitter v1.1 API in javascript using A

2019-04-08 10:18发布

Aim - to get the twitter followers of a particular user using javascript

I have tried the below code as a POC-

$(document).ready(function() {
    // Handler for .ready() called.

    $.ajax({
        url: "https://api.twitter.com/1.1/followers/ids.json?callback=?",
        type: "GET",
        data: { cursor: "-1", 
                screen_name: "twitterapi" },
        cache: false,
        dataType: 'json',

        success: function(data) { alert('hello!'); console.log(data);},
        error: function(html) { alert(html); },
        beforeSend: setHeader
    });


    function setHeader(xhr) {
        if(xhr && xhr.overrideMimeType) {
            xhr.overrideMimeType("application/j-son;charset=UTF-8");
        }

        //var nonce = freshNonce();
        //var timestamp = freshTimestamp();
        //var signature = sign(nonce,timestamp);

        //alert(signature);
        //alert(accessToken+"-"+consumerKey);
        //alert(oauth_version+"-"+oauth_signature_method);
        xhr.setRequestHeader('Authorization','OAuth');
        xhr.setRequestHeader('oauth_consumer_key', 'HdFdA3C3pzTBzbHvPMPw');
        xhr.setRequestHeader('oauth_nonce', '4148fa6e3dca3c3d22a8315dfb4ea5bb');
        xhr.setRequestHeader('oauth_signature','uDZP2scUz6FUKwFie4FtCtJfdNE%3D');
        xhr.setRequestHeader('oauth_signature_method', 'HMAC-SHA1');
        xhr.setRequestHeader('oauth_timestamp', '1359955650');
        xhr.setRequestHeader('oauth_token', '1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl');
        xhr.setRequestHeader('oauth_version', '1.0');
    }

});

I calculated the signature values from the Twitter OAuth tool .. This gives me 400 Bad Request error ....

Please let me know what the problem is...

2条回答
甜甜的少女心
2楼-- · 2019-04-08 10:32

The oauth_* fields are all part of the Authorization header string, so they need to be concatenated as shown at the bottom of this page - https://dev.twitter.com/docs/auth/authorizing-request

They should not be presented as separate header fields.

查看更多
Lonely孤独者°
3楼-- · 2019-04-08 10:52

The problem is your request's header, it should be like this:

xhr.setRequestHeader('Authorization','OAuth oauth_consumer_key="HdFdA3C3pzTBzbHvPMPw", oauth_nonce="4148fa6e3dca3c3d22a8315dfb4ea5bb", oauth_signature="uDZP2scUz6FUKwFie4FtCtJfdNE%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp= "1359955650", oauth_token, "1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl", oauth_version="1.0"');

Btw, this javascript library might help you on OAuth's stuff: oauth-1.0a

It support both client side and node.js

Cheers

查看更多
登录 后发表回答