我正在尝试根据Application Only OAuth instructions为Reddit API获取一个OAuth令牌。我的https://oauth.reddit.com/grants/installed_client应用程序是一个已安装的应用程序,所以我的grant_type使用reddit。
目前,我正在运行一个非常短的JS脚本来查询API并获取一个令牌:
const APP_ID = 'MY_APP_ID'
const DEVICE_ID = 'TRACKING_ID_20_TO_30_CHARS'
let form = new FormData()
form.append('grant_type', 'https://oauth.reddit.com/grants/installed_client')
form.append('device_id', DEVICE_ID)
fetch('https://www.reddit.com/api/v1/access_token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${btoa(`${APP_ID}:`)}`,
}),
body: form })
.then(handleResponse)
.then(function(data) {
console.log(data)
})
.catch(error => console.error(error))
function handleResponse(response) {
return response.json()
}
(注意:按原样运行代码片段会给出一个NetworkError,因为这个APP_ID不是真正的,我不想透露我的。)
我得到的回答是:
{
"error": "unsupported_grant_type"
}当我使用REST客户端尝试相同的API请求时,我得到了预期的响应,因此这让我认为问题与JavaScript有关。由于grant_type与说明所说的内容相匹配,因此我不确定如何处理该错误。我希望其他更有OAuth经验的人会知道这里发生了什么。
发布于 2018-04-09 07:36:44
问题在于FormData对象的使用。在故障排除的早期阶段,我在Reddit上找到了this answer,并决定使用它,但这对我来说不起作用。
它以multipart/form-data而不是application/x-www-form-urlencoded的形式提交数据,这是Reddit的OAuth服务器不喜欢的。我写了一个基于this answer的帮助器函数,它完成了这个任务:
function urlEncode(data) {
let out = [];
for (let key in data) {
out.push(`${key}=${encodeURIComponent(data[key])}`);
}
return out.join('&')
}https://stackoverflow.com/questions/49720311
复制相似问题