2017-01-09 84 views
1

我想調用Twitters API並獲取我的鳴叫,所以我可以將它們發佈到我創建的網站上。Axios API Twitter請求不會返回用戶鳴叫

當我運行下面的代碼時,出現錯誤。

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.

我新的API調用不使用PHP - 不知道我在做什麼錯在這裏。

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) 
    }); 
} 

樣品的OAuth串

const DST = `OAuth oauth_consumer_key="${consumerKey}", 
oauth_nonce="${}", 
oauth_signature="${}", 
oauth_signature_method="${}", 
oauth_timestamp="${}", 
oauth_token="${}", 
oauth_version="1.0" 
`; 
+0

'400'表示請求不好。入口點在語法上不正確。 –

回答

-1

一個400 Bad Request錯誤意味着服務器不明白你的要求。在你的情況下,有一個錯誤,阻止請求通過(額外%)。試試這個:

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) 
    }); 
} 

這將解決400 Bad Request錯誤,但你不會得到任何數據回來呢。 Twitter API要求您授權您的請求。瞭解更多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):

+0

我以爲OAuth是用於流式傳輸請求?我設置了一個,但授權標題讓我感到困惑 - 就像我想從那裏發出的那樣。 – user3622460

+0

在我的axions.get中,我要發送我當前的信息+一個名爲Authorization的數組,其中包含所有OAuth內容? – user3622460

+0

您需要在每次請求時設置此標頭,Twitter對此非常嚴格。我用'Authorization'標題更新了我的問題。 –