使用JavaScript调用Reddit API获取AccessToken报401错误如何解决?
问题原因与修正方案
- Authorization头格式错误:Reddit要求Basic认证的内容是
client_id:client_secret拼接后的Base64编码值,不能直接拼接明文字符串。你需要先把你的应用client_id和client_secret用冒号连接,再调用btoa()方法编码后放到Basic后面。 - 请求头与请求体格式不匹配:你手动指定了
Content-Type: application/x-www-form-urlencoded,但实际请求体用的是FormData对象(对应multipart/form-data格式),二者不一致会导致参数解析失败。要么直接构造urlencoded格式的字符串作为请求体,要么删除手动设置的Content-Type头,由浏览器自动生成FormData对应的头信息。 - no-cors模式配置错误:
mode: 'no-cors'会限制自定义请求头的发送,同时你无法拿到正常的JSON响应结果,需要删除这行配置,允许跨域请求。 - redirect_uri一致性要求:你填写的redirect_uri必须和你在Reddit开发者后台创建应用时填写的回调地址完全一致,包括末尾的斜杠、http/https协议都不能有差异。
修正后代码示例
async function fetchToken(returnCode) { // 替换为你自己的应用client_id和client_secret const clientId = "你的client_id"; const clientSecret = "你的client_secret"; // 生成符合要求的Basic认证编码串 const authBase64 = btoa(`${clientId}:${clientSecret}`); // 构造urlencoded格式请求体,和请求头匹配 const reqBody = new URLSearchParams({ grant_type: 'authorization_code', code: returnCode, redirect_uri: 'http://localhost:3000/' }); const response = await fetch('https://www.reddit.com/api/v1/access_token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `Basic ${authBase64}` }, body: reqBody }); const resData = await response.json(); console.log(resData); }
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

