Having spent a lot of time studying this issue, I found a solution for this; In this solution, I do not use basic authentication, but instead used the oAuth authentication protocol. But in order to use basic authentication, you must be able to specify this in "setHeaderRequest" with minimal changes to the rest of the sample code. I hope this helps someone else in the future:
var token_ // variable will store the token var userName = "clientID"; // app clientID var passWord = "secretKey"; // app clientSecret var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint var request = new XMLHttpRequest(); function getToken(url, clientID, clientSecret) { var key; request.open("POST", url, true); request.setRequestHeader("Content-type", "application/json"); request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request request.onreadystatechange = function () { if (request.readyState == request.DONE) { var response = request.responseText; var obj = JSON.parse(response); key = obj.access_token; //store the value of the accesstoken token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function } } } // Get the token getToken(caspioTokenUrl, userName, passWord);
If you use the Caspio REST API for any request, you may need to encode the parameters for a specific request to your endpoint; see Caspio documentation on this subject;
NOTE: encoded Params is not used in this example, but was used in my solution.
Now that you have the token stored from the token endpoint, you can successfully authenticate for the subsequent request from the endpoint of the caspio resource for your application
function CallWebAPI() { var request_ = new XMLHttpRequest(); var encodedParams = encodeURIComponent(params); request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true); request_.setRequestHeader("Authorization", "Bearer "+ token_); request_.send(); request_.onreadystatechange = function () { if (request_.readyState == 4 && request_.status == 200) { var response = request_.responseText; var obj = JSON.parse(response);
This solution only considers how to successfully complete an authenticated request using the Caspio API in pure javascript. I am sure there are still many shortcomings ...
source share