Express应用中Axios POST请求Pinterest OAuth接口报400错误怎么解决?
问题原因
- 参数格式不匹配:axios 直接传入 JS 对象作为请求体时,默认会序列化为 JSON 格式,即使你设置了
Content-Type: application/x-www-form-urlencoded请求头,也不会自动转为表单编码格式。Pinterest OAuth 接口要求提交表单格式参数,不接受 JSON 格式的请求体,因此返回400错误。 - redirect_uri 重复编码:你手动对
redirect_uri做了encodeURIComponent编码,后续表单序列化时会对参数值自动做一次编码,相当于两次编码,会导致和申请授权阶段传入的redirect_uri不匹配,触发参数校验错误。 - 额外说明:
axios.default.post和普通的axios.post功能完全一致,切换调用方式不会解决参数格式的核心问题。
修复方案
首先引入 Node.js 内置的 querystring 模块,用于序列化表单参数:
const qs = require('querystring');
修改后的请求代码如下:
let url = 'https://api.pinterest.com/v5/oauth/token'; let accessTokenRequestBody = { grant_type: "authorization_code", code: code, redirect_uri: redirectUrl // 移除手动的encodeURIComponent编码 } const clientIdAndSecretBase64 = Buffer.from(`${clientId}:${clientSecret}`).toString('base64'); axios.post(url, qs.stringify(accessTokenRequestBody), { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `Basic ${clientIdAndSecretBase64}` } }).then((response) => { let responseData = response.data; console.log(`Pinterest ResponseData = ${JSON.stringify(responseData, null, 2)}`); }).catch((e) => { // 打印接口返回的具体错误信息,方便后续排查其他问题 console.log(`Pinterest AccessToken Error=`, e.response?.data || e.message); });
内容的提问来源于stack exchange,提问作者ololo
相关产品推荐
相关产品推荐

