【问题标题】:XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/token, Angularjs [duplicate]XMLHttpRequest 无法加载 https://accounts.google.com/o/oauth2/token,Angularjs [重复]
【发布时间】:2014-10-07 13:04:24
【问题描述】:

我找不到我的问题的解决方案。我正在尝试通过 OAuth 2.0 获取 google 访问令牌,但我无法使我的 post 方法工作。这是我的代码:

function oauthCallback(url) {
        var code,
            obj, request;
        if (url.indexOf("code=") > 0) {
            code = url.substr(url.indexOf('=') + 1);
            request = $http({
                method: "POST",
                url: GOOGLE_TOKEN_URL,
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                data: 'code=' + code + '&client_id=' + googleClientID + '&client_secret=' + googleClientSecret + '&redirect_uri=' + redirectURI + '&grant_type=authorization_code'
            });
            request.success( function(data) {
                tokenStore['googleToken'] = data.access_token;
            });
            request.error( function(data, status, headers, config) {
                alert('failed!')
            });
            deferredLogin.resolve();
        } else if (url.indexOf("error=") > 0) {;
            deferredLogin.reject(obj);
        } else {
            deferredLogin.reject({error: 'error occured', error_description: 'Unknown', error_reason: "Unknown"});
        }
    }

使用邮递员我有 access_token 所以 url 和数据是正确的。我尝试过this 和 jsonp 以及许多其他答案,但我总是得到相同的结果:

XMLHttpRequest 无法加载 https://accounts.google.com/o/oauth2/token。请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:63342' 因此不允许访问。

我做错了什么?

【问题讨论】:

    标签: javascript angularjs oauth


    【解决方案1】:

    如果您使用 AJAX,您将无法绕过安全性,它总是会用这种方法阻止您。 我看到了 2 个选项。

    1. 将您的 AJAX 请求更改为浏览器重定向。
    2. 在您的服务器上创建一个代理服务器,将请求转发给 google,然后返回响应。

    这看起来像 Google oauth 400 response: No 'Access-Control-Allow-Origin' header is present on the requested resource

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2017-04-28
      • 2015-03-16
      相关资源
      最近更新 更多