Search code examples
node.jscurloauth-2.0axiosaccess-token

Converting Curl to Nodejs Axios - Obtaining an Access Token


I am currently using curl in order to obtain an access token so I can consume an api with said token. The curl command I use is as follows:

curl --user <client_id>:<client_secret> https://api.ed-fi.org/v3/api/oauth/token --data 'grant_type=client_credentials'

It works and all...but instead of curling I want to utilize the axios library to get this access token instead.

Here's what I have but it doesn't work.

const buff = new Buffer.from('<client_id>:<client_secret>';
const base64data = buff.toString('base64');

axios({ 
        method: 'POST', 
        url: 'https://api.ed-fi.org/v3/api/oauth/token', 
        headers: {
            Authorization: `Basic ${base64data}`
        },
        data: { 'grant_type': 'client_credentials' } 
    })
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });

I can't figure out what I'm missing or doing wrong?


Solution

  • You should change Content-Type (default for axios is JSON) and pass body just like you did in case of curl:

    axios({ 
            method: 'POST', 
            url: 'https://api.ed-fi.org/v3/api/oauth/token', 
            headers: {
                Authorization: `Basic ${base64data}`,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: 'grant_type=client_credentials' 
        })
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.log(error);
        });