Instagram API access_token request and Access-Control-Allow-

Instagram API access_token request and Access-Control-Allow-Origin

本文关键字:request and Access-Control-Allow- token API access Instagram      更新时间:2024-03-16

上下文

我正在尝试使用Instagram API的服务器端/显式流从其获取访问令牌

当用户成功验证并授权我的应用程序时,Instagram会使用代码参数将用户重定向到我的redirect_uri。一旦我得到了这个代码,我将尝试调用Instagram API,以便获得access_token

问题

我成功地获得了此代码,但为了进行此交换,我必须将代码以及一些应用程序标识参数POST到其access_token端点

$.ajax({
    type: 'POST',
    url: 'https://api.instagram.com/oauth/access_token',
    // Disable credentials as they were enabled by default
    xhrFields: {
        withCredentials: false
    },
    crossDomain: true,
    data: {
        client_id: client_id,
        client_secret: client_secret,
        grant_type: 'authorization_code',
        redirect_uri: callback_http,
        code: token
    },
    }).always(function(res) {
    console.log('Res from Instagram API', res);
    });

问题是我遇到了访问控制允许来源问题:

XMLHttpRequest cannot load https://api.instagram.com/oauth/access_token.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin '[here is my callback_http]' is therefore not allowed access.

我曾尝试使用dataType:'jsonp'作为Ajax调用的参数,但没有成功(401代码)。

有什么想法吗?事先非常感谢您的帮助!

在使用服务器端显式流时,必须使用oauth的服务器端代码,因为跨源请求,它被浏览器阻止。如果只想使用javascript,则使用客户端隐式流

除非它托管在您的域中或您拥有url,否则您不能。

你可以参考这个http://en.wikipedia.org/wiki/Same-origin_policy

如果你是服务器的所有者,你可以使用htaccess来解决你的问题。关于如何解决这个问题也在stackoverflow中。。

编码快乐!:D

使用window.location.htm来避免cors问题

window.location.href=https://api.instagram.com/oauth/authorize/?app_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=${responseType}