FEDEX API OAuth Token请求报错:缺少或重复参数(JS实现)
问题排查与修复
核心错误:你设置了
Content-Type: application/x-www-form-urlencoded请求头,但发送的是JSON格式字符串,Fedex的OAuth接口需要接收表单编码格式的参数,而非JSON,这就导致接口识别不到参数,返回BAD.REQUEST.ERROR。修复方案:将JSON对象转换为表单编码格式的字符串,再发送请求。
修正后的代码:
var input = { "grant_type": "client_credentials", "client_id": "*****", "client_secret": "*****" }; // 将对象转换为表单编码格式字符串 var formData = new URLSearchParams(); for (var key in input) { formData.append(key, input[key]); } var xhr = new XMLHttpRequest(); xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { console.log(this.responseText); } }); xhr.open("POST", "https://apis-sandbox.fedex.com/oauth/token"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(formData);
- 补充说明:
URLSearchParams是浏览器原生API,能便捷生成符合application/x-www-form-urlencoded格式的数据,也可以手动拼接字符串(比如grant_type=client_credentials&client_id=xxx&client_secret=xxx),但用URLSearchParams更可靠,能自动处理特殊字符编码。- 你之前在Python/Postman中能成功,是因为这两个工具默认会把表单参数自动编码为
application/x-www-form-urlencoded格式发送,而JS代码里错误地用了JSON格式。
内容的提问来源于stack exchange,提问作者CollegeMonday
相关产品推荐
相关产品推荐

