Search code examples
javascriptxmlhttprequest

XMLHTTPRequest Returning Bad Request (400) - "Require Param: grant_type"


new to this side of things and can't seem to find the proper syntax. In the POST request payload, I need to include "grant_type=client_credentials" according to the service I'm trying to access. However, I can't find the JavaScript syntax to include the username and password in the request payload. Here is what I have so far (I have removed my key and secret for obvious reasons):

    var request = new XMLHttpRequest();
    var path="https://ops.epo.org/3.1/auth/accesstoken";
    request.onreadystatechange=state_change;

    var encodedData = window.btoa(Key:Secret"); //encode consumer key and secret key

    document.write(encodedData);

    request.open("POST", path, true);
    request.setRequestHeader("Authorization", encodedData);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    request.send(null);

    function state_change() {
        if (request.readyState == "4") //Request finished and response is ready
        {
            if (request.status == "200") {


   alert("Success");
        }
        else {
            alert("Problem retrieving data");
            console.log(this.responseXML);
        }
    }
}

Thanks in advance, been stuck on this for the last few hours.


Solution

  • Just needed to remove null from the send payload and replace with 'grant_type=client_credentials'.

    var request = new XMLHttpRequest();
    var path="https://ops.epo.org/3.1/auth/accesstoken";
    request.onreadystatechange=state_change;
    
    var encodedData = window.btoa("Key:secret"); //encode consumer key and secret key
    
    request.open("POST", path, true);
    request.setRequestHeader("Authorization", encodedData);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
    request.send('grant_type=client_credentials');
    
    function state_change() {
        if (request.readyState == "4") //Request finished and response is ready
        {
            if (request.status == "200") {
                alert("Success");
                document.write(request.responseText);;
    
            }
            else {
                alert("Problem retrieving data");
                console.log(this.responseXML);
            }
        }
    }