Axios API Twitter 请求未返回用户推文

Axios API Twitter request not returning back user tweets

我正在尝试调用 Twitter API 并取回我的推文,这样我就可以 post 在我正在创建的网站上发布它们。

当我运行下面的代码时,我得到一个错误。

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"
 `;

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):