Token from API Call is undefined, but works in CURL

289 views Asked by At

I have an API where I do a POST to get a token. The documentation of the API I have followed is from: https://apiexplorer.csod.com/apiconnectorweb/apiexplorer#/info I have tried the API via curl and it returns a token as intended: enter image description here

Now, I try to do exactly the same but via JavaScript. My code:

      fetch( proxyUrl + ' https://myCompany.csod.com/services/api/oauth2/token', {
    method: 'POST',
    body: 'grant_type=client_credentials&client_id=' + key + '&client_secret=' + secret + "&scope=employee:read",
    headers: {
        'Content-Type': 'application/json',
       
    }
}).then((response) =>console.log(response))
.then((data) => console.log(data));
    };

This will return a 200 response:

enter image description here

But I cannot find the token. I have tried to JSON parse the response etc. but it returns "undefined" or an empty {} json object.

Doing a:

.then(response => response.json()).then(data => console.log(data))

will return the following error at console:

Uncaught (in promise) SyntaxError: Unexpected token T in JSON at position 0

When I try to convert the response to text and console log it out, I get the proxyUrls site.

There is 3 reasons why this fails and not Curl in my mind:

  1. I use proxyUrl for CORS in JavaScript that maybe is the cause.
  2. I console log the response/token wrong.
  3. The JavaScript code is wrong.

Anyone have any idea?

0

There are 0 answers