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

使用Axios调用Pinterest V5 OAuth接口返回Invalid Request Body如何解决

你的代码存在3处核心错误,修正后即可正常请求:

  • 错误1:Content-Type头填写错误,你多写了一层application前缀,正确值应为application/x-www-form-urlencoded
  • 错误2:Axios 直接传入JS对象作为请求体时,默认会序列化为JSON格式,即使你设置了form-urlencoded的请求头也不会自动转换格式,需要手动将对象序列化为form-urlencoded格式
  • 错误3:不需要手动对参数做encodeURIComponent转义,序列化工具会自动处理转义逻辑,手动转义反而会导致参数二次转义出错

你可以直接使用Node原生支持的URLSearchParams处理form参数,无需额外安装依赖,修复后的完整代码如下:

const redirectUrl = process.env.PINTEREST_OAUTH_CALLBACK_URL;
const clientId = process.env.PINTEREST_APP_ID;
const clientSecret = process.env.PINTEREST_APP_SECRET;
const url = 'https://api.pinterest.com/v5/oauth/token';

// 用URLSearchParams序列化form参数,无需手动转义
const accessTokenRequestBody = new URLSearchParams({
    code: code, 
    grant_type: "authorization_code",
    redirect_uri: redirectUrl
});

const clientIdAndSecretBase64 = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
axios.post(url, accessTokenRequestBody, {
    headers: {
        // 修正Content-Type
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Authorization': `Basic ${clientIdAndSecretBase64}`
    }
}).then((response) => {
    const responseData = response.data;
    console.log(`Pinterest ResponseData = ${JSON.stringify(responseData, null, 2)}`);
}).catch((e) => {
    console.log(`${JSON.stringify(e.response.data)}`);
});

如果你使用的Node版本较低不支持URLSearchParams,也可以安装qs库,调用qs.stringify(参数对象)完成序列化即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:21:01