You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Axios获取PayPal沙箱OAuth2令牌时出现循环结构错误

解决Axios请求PayPal沙箱OAuth令牌的循环结构错误及空响应问题

1. 修复循环结构序列化错误

你碰到的Converting circular structure to JSON错误,核心原因是模板字符串拼接时触发了非预期的对象序列化。即便你目标是response.data,但在请求异常场景下,模板字符串会隐式尝试序列化包含循环引用的响应对象(比如ClientRequest、TLSSocket这类带内部引用的对象),从而抛出错误。

修改日志输出方式,避免模板字符串与JSON序列化的冲突:

// 替换原日志代码,直接打印对象无需拼接
console.log('response data:', response.data);
// 如需格式化JSON输出,单独处理
console.log('response data (formatted):', JSON.stringify(response.data, null, 2));

2. 修正请求配置细节

PayPal OAuth令牌请求有两个容易忽略的配置点:

  • 虽然URLSearchParams会让Axios自动设置Content-Type,但手动显式声明可避免环境/版本差异导致的异常
  • Accept头应设置为application/json,因为PayPal返回的是JSON格式数据,无需使用application/x-www-form-urlencoded

调整后的Axios请求代码:

const response = await axios.post(
    'https://api-m.sandbox.paypal.com/v1/oauth2/token',
    new URLSearchParams({
        'grant_type': 'client_credentials'
    }),
    {
        auth: {
            username: process.env.PP_CLIENT,
            password: process.env.PP_SECRET
        },
        headers: {
            'Accept': 'application/json', // 匹配返回数据格式
            'Content-Type': 'application/x-www-form-urlencoded', // 显式声明请求格式
            'Accept-Language': 'en_US'
        }
    }
);
console.log('response data:', response.data);

3. 解决Fetch请求空响应问题

Fetch API不会自动解析响应体,必须手动调用解析方法才能获取有效数据。正确的Fetch请求代码:

const PP_CLIENT = process.env.PP_CLIENT;
const PP_SECRET = process.env.PP_SECRET;

const fetchResponse = await fetch('https://api-m.sandbox.paypal.com/v1/oauth2/token', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Basic ${Buffer.from(`${PP_CLIENT}:${PP_SECRET}`).toString('base64')}`,
        'Accept': 'application/json',
        'Accept-Language': 'en_US'
    },
    body: new URLSearchParams({ grant_type: 'client_credentials' })
});

// 调用json()解析响应体,否则只会得到空的Response对象
const data = await fetchResponse.json();
console.log('fetch response data:', data);

4. 额外排查方向

  • 检查Node.js版本:旧版本Node.js的URLSearchParams或Axios兼容性可能存在问题,建议使用LTS版本
  • 确认网络环境:如果服务器处于代理网络下,需为Axios/Fetch配置代理参数,否则可能因请求拦截导致响应结构异常

内容的提问来源于stack exchange,提问作者Benedikt Bergenthal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:55:27