无法使用jQuery执行POST请求以获取Strava OAuth令牌
Unable to perform POST request using jQuery to obtain Strava OAuth token
在尝试使用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
相关文章:
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- jquery试图按名称获取按钮位置
- 如何在jQuery中获取元素的形式
- 如何在php文件中获取$.post-ajax传递的值
- 在Shopify中获取博客文章的图片
- 使用Javascript获取所选选项ID
- 在jQuery中获取表的行索引
- 使用jquery将mysql数据获取到新的表行中
- 在动态创建的元素上获取对特定选择器的引用
- 从城市名称获取惊喜
- Angular只从数组中获取所需的数据
- 无法将数据从firebase获取到我的html页面
- 从ajax请求中获取javascript对象
- 如何从画布上的某个移动事件中获取X和Y
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 如何在PHP中使用$_POST获取Select元素值
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- 从Rally获取一个特定的标记,以便计算另一个字段中的值
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 无法使用jQuery执行POST请求以获取Strava OAuth令牌