制作jQuery的$就调用Twitter的API 1.1搜索Twitter、jQuery、API

2023-09-11 22:28:26 作者:偏痴

下面是一个调用Twitter的搜索API来获取所有的鸣叫从已知有微博,#fml标签的一个很简单的例子。

Here is a very simple example of a call to Twitter's search API to get all tweets from a tag known to have tweets, #fml.

我相信我是正确使用的应用程序,唯一的身份验证如下解释: HTTPS ://dev.twitter.com/docs/auth/application-only-auth (见第3步,例如呼叫)

I believe I am correctly using the application-only authentication as explained here: https://dev.twitter.com/docs/auth/application-only-auth (see Step 3 for example of a call)

我被要求不涉及任何服务器端code,所以我包括承载code在JavaScript中,这是不好的,开始了一个解决方案,但是....

I am being asked for a solution that does not involve any server-side code so I am including the bearer code in the javascript, which isn't good to begin with, but....

我希望这code工作。相反,它产生的错误'400(错误请求)。任何想法?

I would expect this code to work. Instead it produces the error '400 (Bad Request)'. Any ideas?

$.ajax({
    url: "https://api.twitter.com/1.1/search/tweets.json",
    dataType: "jsonp",
    data: "q=%23fml",
    beforeSend:  function (xhr) { 
             xhr.setRequestHeader ("Authorization", "Bearer XXmyBearerCodeXX"); 
            },
    success: function(json){ alert(json); }
});

修改1 - 验证Twitter的通话

使用 hurl.eu 我能够得到与上面的查询和授权标头中的API的成功响应,所以我想这意味着我的微博呼吁是正确的,只是没有正确设置内jQuery.ajax(),但我看不出有什么缺失。

Using hurl.eu I was able to get a successful response from the API with the above query and Authorization header, so I assume this means my Twitter call is correct, just not set up correctly within jQuery.ajax(), but I just don't see what is missing.

推荐答案

您无法使用AJAX由于数据类型JSONP调用设置请求头。

You cannot set request headers using AJAX calls with dataType JSONP.

请参阅这个问题:设置头与jQuery.ajax和JSONP

最好的解决方法是使用一个服务器端代理做搜索为您服务。我知道你正在寻找一个客户端唯一的解决办法,但这种限制,并与周围的CORS没办法,这是怎么回事似乎是今天做了Twitter的API。

The best solution is to use a server-side proxy to do the search for you. I know you are looking for a client only solution, but with this restriction, and with no way around CORS, this is how it seems to be done today for the Twitter API.

修改使用诸如雅虎的YQL 的代理,如果你没有它可能会访问一个。

Edit It may be possible using a proxy like Yahoo's YQL if you don't have access to one.

 
精彩推荐
图片推荐