[SOLVED] Getting access token works with cURL but not Fetch?

Hey there. Attempting to build a browser-based integration but having some trouble getting an access token.

This cURL command works:
curl -X POST -d 'grant_type=password&username=MY_USERNAME&password=MY_PASS&client_id=MY_ID&client_secret=MY_SECRET' https://beta.online-go.com/oauth2/token/

I get an access token just fine.

This fetch() does not:

    function getAccessToken() {
      var theBody = JSON.stringify({
          grant_type: 'password',
          username: OGS_USERNAME,
          password: OGS_PASSWORD,
          client_id: CLIENT_ID,
          client_secret: CLIENT_SECRET,
        });

      fetch(`https://${BETA ? 'beta.' : ''}online-go.com/oauth2/token/`, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: theBody,
      })
      .then(response => response.json())
      .then(data => {
        console.log(data);
      });
    }

I get {error: “unsupported_grant_type”}. Is this a CORS issue in disguise? Something I’m missing? Everything else is identical as far as I can tell. My oauth2 application settings are Client typepublic and Authorization Grant Typepassword.

Any help would be appreciated! Tagging in @flovo and @matburt :slight_smile:

1 Like

You have to use FormData instead of JSON.

var data = new FormData();
data.append('grant_type', 'password');
data.append('username', OGS_USERNAME);
data.append('password', OGS_PASSWORD);
data.append('client_id', CLIENT_ID);
data.append('client_secret', CLIENT_SECRET);

fetch(`https://${BETA ? 'beta.' : ''}online-go.com/oauth2/token/`, {
    method: 'POST',
    body: data,
})
.then(response => response.json())
.then(data => {
console.log(data);
});
3 Likes

That worked! Thanks so much!

1 Like