FedEx授权API请求报错排查:Python正常JS异常
FedEx OAuth API 请求错误排查与修复
错误原因分析
- 参数拼写错误:JavaScript代码中
cliend_id是笔误,正确参数名应为client_id,这会导致API无法识别必填的客户端ID参数,直接触发参数缺失错误。 - 请求体格式不匹配:你设置了
Content-Type: application/x-www-form-urlencoded,但使用JSON.stringify()将参数转为JSON字符串,这与指定的内容类型不兼容。Python的requests.post在传入data=payload时会自动将字典转为URL编码的表单数据,而JavaScript需要手动处理这种格式转换。
修正后的JavaScript代码
const clientId = "****************************"; const clientSecret = "****************************"; // 修正参数拼写错误 const payload = { 'grant_type': 'client_credentials', 'client_id': clientId, 'client_secret': clientSecret }; // 将对象转换为application/x-www-form-urlencoded格式的字符串 const formBody = Object.keys(payload) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`) .join('&'); fetch('https://apis-sandbox.fedex.com/oauth/token', { method: "POST", body: formBody, headers: { "Content-Type": "application/x-www-form-urlencoded" } }) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); // 改用catch捕获请求错误,原写法无法触发错误捕获
额外说明
- 确保所有参数名与API要求完全一致,避免拼写失误。
- 当Content-Type为
application/x-www-form-urlencoded时,请求体必须是key1=value1&key2=value2格式的编码字符串,而非JSON。 - 使用
catch处理请求过程中的网络错误或JSON解析错误,原代码的第三个then无法捕获这类错误。
内容的提问来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

