React Native用fetch请求getmati API Postman正常但返回400错误如何解决
问题根因
- React Native 内置的
fetchAPI 对URLSearchParams类型的请求体处理存在兼容性缺陷,你传入的grant_type参数没有被正确序列化为x-www-form-urlencoded格式,导致服务端无法识别到该参数,返回400错误。
修复方案
你可以选择以下任意一种方式修改代码即可解决问题:
- 直接传入字符串格式的表单参数(兼容性最好)
const myoptions = { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', Authorization: 'Basic 替换为你自己的client_id:client_secret对应的Base64编码值', }, body: 'grant_type=client_credentials', }; fetch('https://api.getmati.com/oauth', myoptions) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err));
- 手动对URLSearchParams执行序列化
如果你要保留URLSearchParams的写法,手动调用toString()方法即可:
body: new URLSearchParams({grant_type: 'client_credentials'}).toString()
额外验证提示
请同时确认你的Authorization请求头中的凭证有效性:Basic 后拼接的内容必须是你的client_id:client_secret组合字符串经过Base64编码后的结果,确保和Postman中配置的一致。
内容的提问来源于stack exchange,提问作者lucky brand
相关产品推荐
相关产品推荐

