[英]Retrieving Facebook Profile Picture URL
我在 MEAN 应用程序中使用 satellizer 进行身份验证。 身份验证完成后,我想获取用户的个人资料图片。 以下是我的代码。
角度控制器
(function(){
'use strict';
angular
.module('nayakans07')
.controller('RegisterController', registerController);
function registerController ($scope, $auth) {
$scope.authenticate = function (provider) {
$auth.authenticate(provider)
.then(function (res) {
console.log(res);
}, authErrorHandler);
};
function authErrorHandler (err) {
console.log(err);
}
}
})();
Node.js 路由处理程序
(function () {
'use strict';
var request = require('request');
var qs = require('querystring');
var tokenHelper = require('../helpers/tokenHelper.js');
var config = require('../config/configuration.js');
var Member = require('../models/memberModel.js');
module.exports = function (req, res) {
var accessTokenUrl = 'https://graph.facebook.com/oauth/access_token';
var grapApiProfileUrl = 'https://graph.facebook.com/me';
var graphApiProfileImageUrl = 'https://graph.facebook.com/me/picture?width=250&json=true';
var params = {
client_id: req.body.clientId,
redirect_uri: req.body.redirectUri,
code: req.body.code,
client_secret: config.FACEBOOK_SECRET
};
request.get({
url: accessTokenUrl,
qs: params
}, function (err, response, accessToken) {
accessToken = qs.parse(accessToken);
request.get({
url: grapApiProfileUrl,
qs: accessToken,
json: true
}, function (err, response, profile) {
console.log(profile);
Member.findOne({
facebookId: profile.id
}, function (err, existingMember) {
if (existingMember) {
return res.status(200).send({
user: existingMember,
token: tokenHelper.createToken(existingMember, req, res)
});
} else {
request.get({
url: graphApiProfileImageUrl,
qs: accessToken,
}, function (err, response, profileImage) {
console.log(profileImage);
var fbData = {
facebookId: profile.id,
fullName: profile.name,
email: profile.email,
profileImage: profileImage
};
return res.status(200).send(fbData);
});
}
});
});
});
};
})();
从 Facebook 获取访问令牌后,我使用访问令牌调用https://graph.facebook.com/me/picture?width=250&json=true
端点以获取个人资料图片链接。 在Facebook 的 API Explorer 中使用令牌调用相同的端点,我得到了个人资料图像 url,但是当我从 node.js 端点处理程序调用它时,我得到了一些二进制数据。 部分回应在这里。
����JFIF���Photoshop 3.08BIM�gtc2XjTON-90Jqu9JFj83(bFBMD01000ac0030000b909000069110000fe120000dc14000069190000c02400002326000029280000872a0000fd3e0000��ICC_PROF
如何获取个人资料图片的 URL 而不是此响应。
不确定您正在使用的 API 版本是否仍然如此,但如果没有传递正确的参数,它曾经导致 301 重定向到图像(尽管他们的 API Explorer 建议...)您可以检查浏览器的网络监控以验证这一点。
这有多种来源,包括官方 Facebook Graph-API 文档,其中指出:
默认情况下,此边缘将返回 302 重定向到图片图像。 要访问有关图片的数据,请在查询中包含 redirect=false。
(来源: https : //developers.facebook.com/docs/graph-api/reference/user/picture/#Reading )
连同一些(较旧但类似的)SO 答案: https : //stackoverflow.com/a/7881978/624590
你有几个选择。 一种是添加redirect=false
查询参数(根据上面的 Facebook 文档)。
另一种选择是通过添加额外的查询参数&fields=url
(我在上面链接的答案建议&fields=picture
,但据我所知,这已经过时了)来明确要求 URL。 如果您需要响应中的高度和宽度,只需将它们添加到查询中: &fields=url,height,width
。 根据我对 Facebook API 的经验,明确要求字段往往是一种更可靠的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.