React Native获取OAuth2.0 Token报unsupported_grant_type错误如何解决
错误原因
React Native 环境的 fetch 方法对 URLSearchParams 类型请求体的处理存在兼容缺陷:既不会自动追加 application/x-www-form-urlencoded 请求头,也无法正确将实例内的参数序列化到请求体中,导致服务端无法识别 grant_type 等必填参数,最终抛出 unsupported_grant_type 错误。
修复方案
方案1:手动构造表单参数(兼容性最好)
直接手动拼接符合 x-www-form-urlencoded 格式的参数,同时明确指定请求头:
const getToken = async () => { // 对key、secret做编码处理,避免特殊字符导致参数异常 const params = `grant_type=client_credentials&client_id=${encodeURIComponent(key)}&client_secret=${encodeURIComponent(secret)}`; const petfinderRes = await fetch( "https://api.petfinder.com/v2/oauth2/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: params, } ); // 先校验请求状态,避免异常响应触发运行报错 if (!petfinderRes.ok) { console.error('请求失败,状态码:', petfinderRes.status); return; } const data = await petfinderRes.json(); console.log('data', data.access_token) setToken(data.access_token); };
方案2:保留URLSearchParams写法
如果不想修改参数构造逻辑,只需增加请求头配置、手动将参数实例转为字符串即可:
const getToken = async () => { const params = new URLSearchParams(); params.append("grant_type", "client_credentials"); params.append("client_id", key); params.append("client_secret", secret); const petfinderRes = await fetch( "https://api.petfinder.com/v2/oauth2/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: params.toString(), } ); if (!petfinderRes.ok) { console.error('请求失败,状态码:', petfinderRes.status); return; } const data = await petfinderRes.json(); console.log('data', data.access_token) setToken(data.access_token); };
内容的提问来源于stack exchange,提问作者Joel Gonzalez
相关产品推荐
相关产品推荐

