将 Curl 转换为 Nodejs Axios - 获取访问令牌

Converting Curl to Nodejs Axios - Obtaining an Access Token

我目前正在使用 curl 来获取访问令牌,这样我就可以使用所述令牌使用 api。我使用的curl命令如下:

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

一切正常...但是我想利用axios库来获取此访问令牌,而不是卷曲。

这是我拥有的,但它不起作用。

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);
    });

我不知道我遗漏了什么或做错了什么?

您应该更改 Content-Type(axios 的默认值为 JSON)并传递 body,就像您在 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);
    });