【问题标题】:Convert CURL Request to Axios将 CURL 请求转换为 Axios
【发布时间】:2021-11-12 19:22:46
【问题描述】:

请问如何将此 curl 请求转换为它的 axios 等效项?

curl -X POST https://api.pinterest.com/v5/oauth/token --header "Authorization: Basic {base64 encoded string made of client_id:client_secret}" --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'grant_type=authorization_code' --data-urlencode 'code={YOUR_CODE}' --data-urlencode 'redirect_uri=http://localhost/'

我为此花了几个小时,只是为了不断得到

 {"code":1,"message":"Invalid request body"}

这是我尝试过的:

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

let accessTokenRequestBody = {
    code: code,
    grant_type: "authorization_code",
    redirect_uri: redirectUrl
};

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

我非常感谢任何帮助,因为这浪费了我很多时间。我目前正赶上最后期限...谢谢。

【问题讨论】:

    标签: javascript node.js curl axios pinterest


    【解决方案1】:

    你需要urlencode参数而不是传递一个对象作为数据。

    const params = new URLSearchParams();
    params.append('redirect_uri', process.env.PINTEREST_OAUTH_CALLBACK_URL)
    // do the same for other parameters
    // ...
    // make post
    

    【讨论】:

      猜你喜欢
      • 2020-02-26
      • 2019-08-17
      • 2021-04-28
      • 2021-05-22
      • 2017-08-03
      • 2018-04-16
      • 2021-02-06
      • 2017-01-13
      • 1970-01-01
      相关资源
      最近更新 更多