2
votes

I am trying to call Twitters API and get a my tweets back so I can post them on a website I am creating.

When I run the following code I get an error.

XMLHttpRequest cannot load https://api.twitter.com/1.1/search/tweets.json?q=%SamSchaeferSays. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3333' is therefore not allowed access. The response had HTTP status code 400." And "bundle.js:30041 Uncaught (in promise) Error: Network Error.

I am new to API calls not using PHP - not sure what I am doing wrong here.

const tweet = 'https://api.twitter.com/1.1/search/tweets.json?q=%SamSchaeferSays';
function getUserTweet() {
    return axios.get(`${tweet}`).then(function(response){
        console.log(response.data)
        console.log(response.status)
    });
}

sample OAuth string

const DST = `OAuth oauth_consumer_key="${consumerKey}",
oauth_nonce="${}", 
oauth_signature="${}", 
oauth_signature_method="${}", 
oauth_timestamp="${}", 
oauth_token="${}", 
oauth_version="1.0"
 `;
1
400 means bad request. entry point is not syntactically correct. - devellopah

1 Answers

2
votes

A 400 Bad Request error means that the server doesn't understand your request. In your case there's a typo that prevents the request from going through (extra %). Try this:

const tweet = 'https://api.twitter.com/1.1/search/tweets.json?q=SamSchaeferSays';
function getUserTweet() {
    return axios.get(`${tweet}`, { headers: { 'Authorization': 'YOUR_OAUTH_HEADER' } }).then(function(response){
        console.log(response.data)
        console.log(response.status)
    });
}

This will fix the 400 Bad Request error, but you won't get any data back yet. The Twitter API requires you to authorize your request. Find out more in their documentation.

To allow applications to provide this information, Twitter’s API relies on the OAuth 1.0a protocol. At a very simplified level, Twitter’s implementation requires that requests needing authorization contain an additional HTTP Authorization header with enough information to answer the questions listed above. A version of the HTTP request shown above, modified to include this header, looks like this (normally the Authorization header would need to be on one line, but has been wrapped for legibility here):