Skip to content Skip to sidebar Skip to footer

Connecting Via OAuth2 With JQuery/AJAX For Box.com

I'm trying to work with Box.com's API to develop a quick app that allows for Folder creation. I am having trouble connecting to their API and am fairly new to oAUTH2, API's, and wh

Solution 1:

I did find a way to connect to their API and get a token, but now I am getting a CORS error when I try and send a POST request to their server to create a folder (the main goal of my app) for anyone interested.. here is how I trade off the code for the token

authorizeUser = function(){    

        var results = $.ajax({

            // The URL to process the request
            url : 'https://www.box.com/api/oauth2/token',
            type : 'POST',
            data : {
                grant_type : 'authorization_code',
                code : data.boxAuthorizationCode,
                client_id : data.clientId,
                client_secret : data.clientSecret
            },
            beforeSend: function (xhr) {
  xhr.setRequestHeader("Authorization", "Bearer $token")
},
            dataType: "json",
            success: function(response) {
               //console.log(response);
               console.log(response.access_token);
               data.access_token = response.access_token;
               tokenGranted();
            }

        });

        return results.responseText;

    },

Solution 2:

You can use Axios instead of ajax

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.9.4/qs.js"></script>

After requiring this script you can write your own javascript function and it will work.

clientId: Pass dynamic client id. secret: Pass dynamic secret.

      async  function runAuthQuery(params) {
          const config = {
          url: '{WebURL}',
          method: 'post',
          data: Qs.stringify({
            grant_type: 'client_credentials',
            client_id: clientId,
            client_secret: secret,
          })
        };
        const bearerToken = await axios(config);
        const getPlayableUrl = await axios.get(`{WebURL}`,
          {
            "headers": {
              "content-type": "application/x-www-form-urlencoded",
              "authorization": `Bearer ${bearerToken.data.access_token}`
            }
          });
        }

It is working fine for me.


Post a Comment for "Connecting Via OAuth2 With JQuery/AJAX For Box.com"