无法使用jQuery执行POST请求以获取Strava OAuth令牌

Unable to perform POST request using jQuery to obtain Strava OAuth token

本文关键字:获取 Strava OAuth 令牌 请求 POST jQuery 执行      更新时间:2023-09-26

在尝试使用Strava API检索访问令牌时遇到问题:https://strava.github.io/api/v3/oauth/

我最初的代码请求和回调功能正常,但当尝试访问/oauth/token URL时,我会以两种不同的方式失败。第一:

        console.log('Posting to /token with code: ' + code);
        Ember.$.ajax({
            type: 'POST',
            url: 'https://www.strava.com/oauth/token',
            data: 'client_id=<myid>&client_secret=<mysecret>&code=' + code,
            success: function(data) {
                var jsonData = JSON.stringify(data);
                var accessToken = jsonData.access_token;
                console.log('Received access token: ' + accessToken);
                if (accessToken) {
                    this.get("controllers.application").set('settings.strava.accessKey', accessToken);
                }
            },
            error: function(jqXHR, textStatus) {
                console.log('API auth error occurred: ' + JSON.stringify(error));
                throw new Error(error);
            }
        });

打印Posting to /token with code: 3ae248f...,HTTP请求返回200响应(在Chrome调试器的"网络"选项卡中),但我实际上无法查看调试器中的响应内容/数据,浏览器控制台抱怨:

XMLHttpRequest无法加载https://www.strava.com/oauth/token.不请求的上存在"Access Control Allow Origin"标头资源原点'http://localhost:4200因此不允许通道

但是,如果我在上面的请求中添加一些选项:

        crossDomain: true,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'DELETE, HEAD, GET, OPTIONS, POST, PUT',
            'Content-Type': 'application/json;charset=UTF-8'
        },

然后,一个OPTIONS请求首先发出(到/oauth/token端点),然后返回302 Found,但我在浏览器控制台中看到一个不同的错误:

XMLHttpRequest无法加载https://www.strava.com/oauth/token.飞行前的响应无效(重定向)

CORS不是我有丰富经验的东西,这是我没有想法的地方。

以下在我的Cordova应用程序中运行良好:

var c_id = "YOUR_ID_HERE";
var c_secret = "YOUR_SECRET_HERE";
var access_code = "YOUR_AUTH_HTTP_CODE_HERE";
var params = "client_id=" + c_id + "&client_secret=" + c_secret + "&code=" + access_code;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    alert(xmlhttp.responseText);
  }
}
xmlhttp.open("POST", "https://www.strava.com/oauth/token", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);

对于飞行前请求,响应应以状态200 Ok结束,并且至少包含Access-Control-Allow-Origin: your origin