使用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
相关产品推荐
相关产品推荐

