我使用javascript sdk,我试图从Facebook帐户获取公共帖子。 这是我用于设置ajax和获取访问令牌的代码(我在请求中使用我的应用程序密钥,因为该程序只在我的计算机上运行,并且没有客户端暴露给它)。Facebook的发布请求有时会让我的帖子,有时不(很奇怪)
<head>
<title>Hopfully Facebook</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">//connect to ajax</script>
</head>
<body>
<script>
var token;
$.ajax({url: "https://graph.facebook.com/oauth/access_token?\client_id=APPID&client_secret=APPSECRET&grant_type=client_credentials",
success: function(result){
token = result.access_token; //in this var the access_token is stored
}); // end of the access_token request
</script>
这是javascript sdk的设置和第一篇文章的请求。
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'APPID',
xfbml : true,
version : 'v2.9'
}); //setting up the javascript sdk
var firstPostId;
FB.api(
('/AviBitterOfficial/posts?access_token='+token),
'GET',
{ "limit" : "1"},
function(response) {
console.log(response);
firstPostId = JSON.stringify(response.data[0].id);
firstPostId = firstPostId.substring(1, firstPostId.length -1);
FB.api( // the second call is in the first call's call back in order to bypass the async problem
('/'+ firstPostId+'?access_token='+token), // that the second call has initialized before the first call back
'GET',
{"fields":"message"},
function(response) {
alert(response.message);
}
);
}
);
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
每次运行该程序时,它都会生成相同的密钥,但是它的问题有点奇怪。当我使用该令牌进行api调用以获取帖子的文本时,它有时会打电话给我,但有时会给我这个错误“无效的OAuth访问令牌”。代码109. 这很奇怪,因为在api调用成功的时候,以及在这两个时代它都给我带来了错误,令牌是一样的,其他所有东西都是一样的。 有没有人有任何建议?
@luschm我对网络编程非常陌生,所以我可能会做一些我不应该做的事情,但我只需要得到一些帖子和他们的信息,我不认为我必须在不久的将来做这样的事情。我认为你对问题的发生是因为api是异步的,并且你是否知道控制我所做的调用的顺序? –
将ajax调用放在fbAsyncInit回调函数中,并在成功回调中完成其余部分。 – luschn
非常感谢你,它在我的代码的其余部分工作:)我有一个循环,它在每一轮都发出请求,但由于api的异步性,请求按错误顺序完成'你知道一种方法来解决这个问题? @luschn –