【发布时间】:2021-12-06 23:40:59
【问题描述】:
要记住几件事,我是一个相当初学者的计算机科学专业学生,有几个大项目。我大部分时间都在使用 java,所以 web 有点新,但似乎很容易习惯。
我正在尝试向将返回我需要的会员 ID 的端点发送发布请求。
我一直在尝试遵循这两个文档/指南:
https://github.com/Bungie-net/api/wiki/OAuth-Documentation
https://lowlidev.com.au/destiny/authentication-2#/tab-popup
顺便说一句,我真的觉得没有多少“入门”指南用于使用 Bungie API,但也许这是为了防止人们对人们的帐户做愚蠢的事情。
无论如何,我已经成功完成了第一部分,即使用 Bungie 提供的我的客户端 ID 使用用户帐户授权我的应用程序(在 bungie 开发者网站上注册)。这会在 url 中返回一个代码,该代码是您对用户帐户的授权代码。我有一种从网址中提取它的笨拙方式,所以任何关于我如何改进它的想法都将不胜感激。
document.getElementById("authButton").addEventListener("click", function(event) {
location.href = "https://www.bungie.net/en/OAuth/Authorize?client_id={my-client-id}&response_type=code&state=" + makeState(32);
});
var authCode = undefined;
if (window.location.href.includes("code=")) {
removeAuthButton();
authCode = window.location.href;
console.log(authCode);
var codeLoc = authCode.indexOf("code=");
var codeEndLoc = authCode.indexOf("&", 15);
authCode = authCode.substring(codeLoc + 5, codeEndLoc);
console.log(authCode);
}
此代码只是在网页中按下一个简单的授权按钮后执行,当我注册我的应用程序时,bungie 会为我处理重定向回我的页面。
在此之后,文档显示了我需要使用以下内容发出的 POST 请求:
POST https://www.bungie.net/platform/app/oauth/token/ HTTP/1.1
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
为了保持 urlencoded 格式,我使用我找到的答案尝试了此代码:
https://stackoverflow.com/a/53189376/16910197
document.getElementById("linkButton").addEventListener("click", function(event) {
fetch('https://www.bungie.net/Platform/App/OAuth/token/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
'client_id': "{my-client-id}",
'grant_type': "authorization_code",
'code': authCode
})
}).then(function(response) {
console.log(response);
return response.json();
});
});
这不起作用,我已尽一切可能对其进行了修改以尝试使其正常工作但无济于事。我错过了什么?
如果需要,我会返回以下内容:
Response { type: "cors", url: "https://www.bungie.net/Platform/App/OAuth/token/", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
我对stackoverflow有点新,这是我的第一个问题,所以如果我可以更好地格式化它,请告诉我。
【问题讨论】:
标签: javascript api rest