我正在尝试调用 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/