【发布时间】:2018-07-06 02:49:13
【问题描述】:
在问这个问题之前,我已经提到了以下内容,但没有帮助我
- Passport.js & Facebook Graph API
- Retrieving photo from Facebook using passport-facebook
- https://www.hitchhq.com/facebook-graph-api/docs/facebook-authentication
- http://tech.bigstylist.com/index.php/2017/08/12/search-facebook-graph-api-nodejs/
- How to use Facebook Graph API after authenticating with Passport.js facebook strategy? enter link description here
有些帖子说要使用passport-facebook-token,但我不想使用,因为我想仅使用passport-facebook 扩展我的应用程序的现有功能
问题陈述
目前,我正在使用 passport-facebook 进行身份验证,效果很好,现在我想扩展功能以使用 Facebook Graph API 来获取登录到我的应用程序的用户的照片
所以使用 Facebook Graph API 来获取我必须使用 Node JS 中的请求模块在下面调用的用户照片,正文部分将返回我预期的结果
var request = require("request");
var options = {
method: 'GET',
url: 'https://graph.facebook.com/me/photos/',
qs: {
access_token: 'EBBCEdEose0cBADwb5mOEGISFzPwrsUCrXwRWhO87aXB9KsVJlgSLc19IdX9D9AKU7OD5SdFOqPXW3eLm8J3HltZC14VexdMsEDW35LDWASdVDNGp5brFERBETsIvxXJIFXo7QSum5apHXeRyQk7c2PQljmf5WHObZAwXVzYjqPd4lziKTUK48Wfrw5HPwZD'
},
headers: {
'content-type': 'application/json'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
但现在我想创建我的自定义 express GET API,当我调用它时,我使用的应该是获得上述正文响应,
点赞GET : /graph/photos
app.get('/graph/photos', function (req, res) {
res.send(body)//Here I wanted to get the same response as of the request module above
});
但我有以下挑战
- 从 passport-facebook 获取 access_token 并将其传递给请求模块
- 如果用户未通过身份验证,API 响应中会抛出错误
但我可以通过以下方法进行一些操作,我已按照
中的教程进行操作https://github.com/scotch-io/easy-node-authentication/tree/linking
app.get('/graph/photos', isLoggedIn, function (req, res) {
var hsResponse = request({
url: 'https://graph.facebook.com/me/photos',
method: 'GET',
qs: {
"access_token": req.user.facebook.token
},
}, function (error, response, body) {
res.setHeader('Content-Type', 'application/json');
res.send(body);
});
});
但我面临的问题是每次调用 API /graph/photos/ 时,它都会尝试重定向以检查用户是否已登录,因此 我将无法直接在 Angular 服务中使用并低于错误
错误
无法加载 http://localhost:3000/graph/photos:从“http://someurl”重定向到“http://someurl”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头.因此不允许访问 Origin 'http://localhost:4200'。
【问题讨论】:
-
您是否从 localhost 以外的其他地方尝试过这个? CORS 标头有时未在 localhost 上设置(例如,在 Chrome 中,您需要扩展才能使其工作)。
-
@KeatsPeeks 关于 CORS 错误是正确的。您可以尝试使用其他浏览器,但默认情况下 Chrome 不允许 localhost 到 localhost 访问。一种可能的纠正方法是启用cors middleware on the node server。
-
谢谢,KeatsPeeks RickyM 但我想要通用解决方案,很多人使用 Chrome 浏览器
-
@Batman 你不明白,我们只是在谈论 localhost,“人”不会使用 localhost 来使用你的网站。将其安装在某个地方,然后重试。 -
-
哦,好吧,让我在真实服务器上检查并检查
标签: node.js facebook facebook-graph-api passport.js passport-facebook