node-fetch to return bearer token

13 views Asked by At

I am trying to use node-fetch to return the bearer token in a function. I am having issues though and the following:

import fetch from 'node-fetch'


export class APIToken {


    async getToken() {

        const tenant_id = '123';

        const formData = new URLSearchParams();
        formData.append('grant_type', 'password');
        formData.append('scope', 'api://');
        formData.append('client_secret', '123');
        formData.append('client_id', '456');
        formData.append('username', '[email protected]');
        formData.append('password', 'password!!');
    
        const response = await fetch(`https://login.microsoftonline.com//${tenant_id}//oauth2/token`, {
            method: 'POST',
            body: formData
            
        });
        const responseBody = await response.json();
        const accessToken = responseBody.access_token;
        return accessToken

    }
}

Results in:

responseBody is of type 'unknown'

On this line:

const accessToken = responseBody.access_token;
1

There are 1 answers

0
JD2775 On

Found the issue. I had to install a different version of node-fetch

npm install node-fetch@2

instead of

npm install node-fetch

That cleared up my issue. It was errors relating to switching to ESM