Ajax REST API Twitter授权问题:错误400错误请求

时间:2014-01-27 11:51:02

标签: javascript jquery ajax twitter twitter-oauth

我无法通过JQuery对Twitter API进行Ajax调用。我的问题是授权。这就是我正在做的事情,对我来说似乎没问题:

function loadTwitter(sLat, sLon, sRad, dFrom, dTo){
            arrayTweets = new Array();
            var sRadKm = sRad/1000;
            dFrom = dFrom/1000;
            dTo = dTo/1000;
                    var twitterUrlPath = "https://api.twitter.com/1.1/search/tweets.json";
            var auth = "OAuth oauth_consumer_key='0kfWFbA6xxxrKjpg2oQ', oauth_nonce='87abf089674bxxx8bd50823c500c', oauth_signature='URF2O%2BdSS0ExxxP8pqQWnA%3D', oauth_signature_method='HMAC-SHA1', oauth_timestamp='1390287341', oauth_token='2287933520-fuUBrz3AZ0GoopxxxxsfE4nLZZ5QJryB8cFZuR0', oauth_version='1.1'";
            var urlTwitter = "?geocode=" + sLat + "," + sLon + "," + sRadKm + "km&count=100"; 
            $.ajax({
                    type: "GET",
                    async: false,
                    accept: "application/json",
                    url: twitterUrlPath + urlTwitter,
                    dataType: "jsonp",
                    beforeSend : function(req) {
                        req.setRequestHeader('Authorization', auth);
                    }, 
                    success: function (resp, status, xhr) {
                       $("#message").html("STATUS: " + xhr.status + " " + xhr.statusText + "\n" + resp);
                       $("#message").hide();
                       $.each(resp, function() {
                            $.each(this, function(i, item) {
                                arrayTweets.push(item);
                            });

                        });

                        displayTweets();
                    },
                    error: function(resp, status, xhr){
                        $("#message").html("ERROR: " + xhr.status + " " + xhr.statusText + "\n" + resp.e);
                        $("#message").show();
                    }
                });
        }

我一直收到400 Bad Request。

另外,如果我想通过海报(firefox嗅探器)调用它,我该如何传递auth参数? 谢谢,

1 个答案:

答案 0 :(得分:0)

所以...我们在尝试解决这个问题时遇到了同样的问题,但我仍然感到困惑的是Twitter不支持客户端授权的数据请求,这就是我们管理它的方式:

由于我们正在处理jsonp调用,因此您无法在调用ref中实际包含标头。 How can I access auth-only Twitter API methods from a web application

所以setRequestHeader是不行的。

你需要做的是在jquery ajax请求的url中构建整个请求,但是这里还有一些需要注意的注意事项:

当您为签名创建基本URL时,它需要是您要发送到Twitter的EXACT URL,例如,您需要在签名过程中定义的回调(您希望在服务器端执行),所以这样的事情:

    parameters = {
        callback:"callback",
        q:"1",
        oauth_consumer_key : [your consumer key],
        oauth_token : [token from initial oauth call],
        oauth_nonce : [random alphanumeric 32 bytes base64],
        oauth_timestamp : Math.round(today.getTime()/1000),
        oauth_signature_method : 'HMAC-SHA1',
        oauth_version : '1.0'
    }; 

创建签名服务器端我建议使用这个lib: https://github.com/mikeal/oauth-sign/blob/master/index.js

然后在客户端通过jquery ajax做一些请求:

    $.ajax({
        type: "GET",
        accept: "*/*",
        contentType: "application/x-www-form-urlencoded",
        dataType: "jsonp",
        jsonpCallback: "callback",
        cache: true,
        url: "https://api.twitter.com/1.1/search/tweets.json?" + "q=1" + this.authString,
        success: function (data, bla, test) {
            console.log(data, bla, test);
        },
        error: function (data) {
            console.log(data)
        }
    });

如果你注意到缓存设置为true,这意味着jquery不会在url调用上附加时间戳重要的sonce url应该反映签名库url也注意我们再次定义了jsonpCallback以反映确切的基本URL。 / p>

确保在客户端编码url调用的值,这里我们重用lib中的函数:

SearchQuery.prototype.encodeRFC3986 = function (str) {
    return encodeURIComponent(str)
        .replace(/!/g, '%21')
        .replace(/\*/g, '%2A')
        .replace(/\(/g, '%28')
        .replace(/\)/g, '%29')
        .replace(/'/g, '%27')
        ;
}

例如

authString += "&" + this.encodeRFC3986("oauth_signature") + "=" + this.encodeRFC3986(this.searchObj.signature);