【发布时间】:2016-09-05 06:18:07
【问题描述】:
要使用 Instagram API 对应用中的用户进行身份验证,请将用户重定向到 URL https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code。
一旦用户在此页面上登录,Instagram 就会向重定向 URI(上述 URL 中的 REDIRECT-URI)发出 GET 请求。此对重定向 URI 的调用包含一个代码,然后您必须将其包含在对 https://api.instagram.com/oauth/access_token 的 POST 请求中,以交换在响应中以 JSON 形式发送的访问令牌。
所以我正在接收重定向调用并使用我的 Express API 请求访问令牌,这工作正常,我得到了带有访问令牌的表单。
app.get('/redirect', function(req, res){
if(req.query.error){
console.log('Error authenticating user');
console.log(req.query.error);
}
else{
request.post(
'https://api.instagram.com/oauth/access_token',
{form:{
client_id: 'my_client_id',
client_secret: 'my_client_secret',
grant_type: 'authorization_code',
redirect_uri: 'http://localhost/redirect',
code: req.query.code
}
},
function(error, response, body){
if(!error && response.statusCode == 200){
console.log(body);
//HOW DO I GET THIS RESPONSE TO ANGULAR?
res.json({
access_token: body.access_token,
full_name: body.full_name,
username: body.username,
profile_picture: body.profile_picture,
id: body.id
});
return;
}
else{
console.log(response);
console.log(body);
}
}
);
};
我的问题是: 如何将访问令牌(或错误响应)发送回 Angular?
换句话说,Angular 如何从它没有发出的请求中接收响应(因为我想要接收的响应来自使用 NodeJS 的request 发出的请求)?
最初我尝试使用 Angular 将第一个 GET 设置为 https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code,但我认为这无法做到,因为用户应该被引导到 Instagram URL 以登录。
更新:
当 Instagram 发出 GET /redirect?code=xxxxxx 时,它会将请求发送到我的 API,但也会将页面 URL 更改为 http://localhost/redirect?code=xxxxxx。我可以在我的 API 中接收访问令牌并将其发送到我的客户端,但由于上述 URL,该页面仅显示为响应的文本,而不是我的 index.html 和 ng-view。在这种情况下,如何让页面成为我的index.html?
我尝试了以下方式使用 angular-router,但均未奏效:
.when('/redirect', {
templateUrl: 'views/success.html',
controller: 'Controller'
})
和
.when('/success', {
templateUrl: 'views/success.html',
controller: 'Controller'
})
.when('/redirect', {
redirectTo: '/success'
})
【问题讨论】:
标签: angularjs node.js http express instagram-api