我正在尝试从 Instagram 接收 token ,但遇到了一些问题。我使用此代码,但出现以下错误:
SEC7127:CORS 请求的重定向被阻止。
SCRIPT7002:XMLHttpRequest:网络错误 0x2ef1,由于错误 00002ef1,无法完成操作。
$(document).ready(function() {
var clientId = 'xxx';
var clientSecret = 'xxx';
var redirectUri = 'http://localhost/instagramFeed/';
function callback(code) {
$.ajax({
type: 'POST',
client_id: clientId,
client_secret: clientSecret,
grant_type: authorization_code,
redirect_uri: redirectUri,
code: code,
success: function(code) {
console.log('Callbeck success!');
},
error: function(msg) {
console.log('Error in callback');
console.log(msg);
}
});
}
var requestToken = function() {
var url = 'https://instagram.com/oauth/authorize/?client_id=' + clientId + '&redirect_uri=' + redirectUri + '&response_type=code';
$.ajax({
type: 'GET',
url: url,
success: function(code) {
console.log('Success' + code);
callback(code);
},
error: function(msg) {
console.log('Error');
console.log(msg);
}
});
};
requestToken();
});
最佳答案
一堆错误:code
将作为重定向 URL 中的 url 参数到达,您无法进行 ajax get 调用并获取 code
作为响应。
并且您不能仅使用 javascript 进行服务器显式 oauth 登录,您必须在服务器端代码上进行发布。
如果你只想使用javascript,那么你可以使用Instagram支持的oauth2的客户端隐式授权方法,你必须启用这是应用程序设置。
您所要做的就是使用 response_type=token
而不是 =code
打开身份验证 URL。
window.location = 'https://instagram.com/oauth/authorize/?client_id=' + clientId + '&redirect_uri=' + redirectUri + '&response_type=token'
只需打开此网址,登录后,access_token
将位于重定向网址
的哈希片段中
要获取它,只需在重定向 URL 页面中添加此代码即可
var access_token = "";
if (window.location.hash){
access_token = window.location.hash.split("access_token=")[1];
window.location.hash = "";
}
更多详细信息请参见:https://www.instagram.com/developer/authentication/
关于javascript - 如何使用 ajax 接收 Instagram 登录 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38433085/