Please how can I convert this curl request to it's axios equivalent?
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/'
I have spent several hours on this only for me to keep getting
{"code":1,"message":"Invalid request body"}
Here is what I tried:
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)}`);
});
I would be really grateful to any help as this has wasted my time so much. I'm currently running behind deadline... Thank you.
CodePudding user response:
You need to urlencode the parameters instead of passing an object as the data.
const params = new URLSearchParams();
params.append('redirect_uri', process.env.PINTEREST_OAUTH_CALLBACK_URL)
// do the same for other parameters
// ...
// make post