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

标签 javascript api reactjs twitter axios

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

当我运行以下代码时,出现错误。

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.

我是不使用 PHP 的 API 调用新手 - 不确定我在这里做错了什么。

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

关于javascript - Axios API Twitter 请求未返回用户推文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41555894/

相关文章:

javascript - Kendo UI Grid Inline - 在网格的特定位置插入新行

javascript - 发送问题 -> 加密 -> 使用 jQuery 和 PHP 获取

api - 在 PUT API 导出中获取队列名称 (MQ_PUT_EXIT)

javascript - Last.fm api 和 & 字符

reactjs - 需要使用 Jest 建议来测试 React/Redux

javascript - 如何将样式应用于带有样式组件的 react-burger-menu 按钮?

javascript - 如何根据keyup统计单词数

javascript - 在 Windows 10 上的 Chrome 中以 HTML(聊天机器人图标)呈现 SVG 文件时出现问题

api - 我们如何设计 .net core api Controller 来接受字符串数组值

javascript - 在此示例中如何将数组值与对象属性进行比较?