Search code examples
javascriptxmlhttprequestaccess-token

Getting an Access Token with Xml HTTP Request


I am having some trouble getting an access token from a site for a web application. The response to the following is

"{"error":"invalid_request","error_description":"The grant type was not specified in the request"}".

I have specified the grant type below but it seems I have not formatted the request correctly.

Any suggestions?

  var getToken = new XMLHttpRequest(); 
  getToken.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  getToken.open("POST", "https://api2.libcal.com/1.1/oauth/token", true); 
  getToken.send('grant_type=client_credentials','client_id=XXX', 'client_secret=XXXXXXXXXXXXXXXXXXXX');

Solution

  • As you are doing a Post Request to get an access token , the parameters should be send in the body (JSON) like below : (I tested ,it works fine )

      // form data for the post request
      var data = {
        "grant_type":"client_credentials",
        "client_id": "XXX",
        "client_secret": "XXXXXXXXXXXXXXXXXXXX"
      };
    
    
      // construct an HTTP request
      var getToken= new XMLHttpRequest();
      getToken.open("POST", "https://api2.libcal.com/1.1/oauth/token", true);
      getToken.setRequestHeader('Content-Type', 'application/json');
    
      // send the collected data as JSON
      getToken.send(JSON.stringify(data));