Error 401: Problems with JSONP token with Twitter REST API Ajax

javascript
error-codes
jsonp
ajax

#1

When trying to perform an API call to Twitter, I noticed I must use “jsonp” to bypass the cross-domain problem. Using “json” dataType will throw a 400 “Control-Allow-Origin” error.

On the other hand, when I’m switching to jsonp I’m always receiving a 400 error with the following message:

jquery.min.js:4 GET https://api.twitter.com/1.1/search/tweets.json?callback=aloha&q=dog

Any ideas on what I’m doing wrong here and how to get it fixed?

function aloha(result) {
    debugger;
};
var twitter_call = $.getJSON({
         type: 'GET',
         contentType: 'application/javascript',
         dataType: 'jsonp',
         cache: true,
         jsonpCallback: 'aloha',
         url: 'https://api.twitter.com/1.1/search/tweets.json',
         crossDomain: true,
         headers: {
            "Authorization": "Bearer MY_BEARER_TOKEN"
         },
         data: {
            "q":"dog"
         }
    });

#2

What you’re trying to do is not supported. We don’t support JSONP, and we don’t allow cross-domain requests from a Javascript web app. You’ll need to use some kind of server-side proxy.


#3

Andy, thanks you for the prompt response. All I want is to return tweets that contain a certain hashtag on my website. What is your suggestion for me to have this working fine? I don’t need to stick with Ajax or JSONP if that doesn’t work. All I want is to present in my website all tweets containing a certain hashtag. What’s your suggestion for this?


#4

You could have a look at Codebird-JS which I think uses a proxy.

Even better than that, you can create a search widget and use our Twitter for websites widgets to display the Tweets - that will also ensure that you comply with our display guidelines.


#5

Andy, I’ve looked at the https://dev.twitter.com/web/embedded-timelines/search, but I don’t believe we can make the hashtag a variable in that case, can we?

On my case, users will perform a search on our website and this search string would then be transformed into a hashtag and used to return all tweets with that hashtag.


#6

I see - no, you would have to configure the hashtag in the widget settings.

In this case, I can only suggest server-side code that your front-end sends the query to, runs the search, and returns the results to the front-end. Again, be aware of the display and branding guidelines, and the API rate limits (which are low on the search endpoint).