Home > database >  Querying the API via JavaScript / CORS (teamup.com calendar)
Querying the API via JavaScript / CORS (teamup.com calendar)

Time:06-06

I am currently trying to figure out how to query the API of a calendar on teamup.com and retrieve data (events in the calendar) from it.

There's a code example on their website: Querying the API via JavaScript / CORS

I tried to make it work in Visual Studio, so I had to install XMLHttpRequest via npm and add a require code line:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

// Creates a CORS request in a cross-browser manner
function createCORSRequest(method, url) {
    var apiKey = 'API_KEY'; //placeholder for api key
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari/IE10 .
        xhr.open(method, url, true);
        xhr.setRequestHeader('Teamup-Token', apiKey);
    } else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE8/IE9.
        xhr = new XDomainRequest();
        // XDomainRequest does not support querying HTTPS from HTTP pages
        if (window.location.protocol === 'http:') {
            url = url.replace('https://', 'http://');
        }
        if (-1 === ['GET', 'POST'].indexOf(method)) {
            alert('XDomainRequest only supports GET and POST methods');
            return;
        }
        if (-1 === url.indexOf('?')) {
            url  = '?_teamup_token='   apiKey;
        } else {
            url  = '&_teamup_token='   apiKey;
        }
        xhr.open(method, url);
    } else {
        // CORS not supported.
        xhr = null;
    }
    return xhr;
}

// Sends the actual CORS request.
function makeCorsRequest(url, successCallback, errorCallback) {
    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
        alert('CORS not supported');
        return;
    }

    // Response handlers.
    xhr.onload = function (xhr) {
        if (xhr.target.status < 400) {
            if (successCallback) successCallback(xhr.target);
        } else if (errorCallback) {
            errorCallback(xhr.target);
        }
    };
    xhr.onerror = function (xhr) {
        if (errorCallback) {
            errorCallback(xhr.target);
        }
    };

    xhr.send();
}

// Send a GET request for all events in a date range
makeCorsRequest(
    'https://api.teamup.com/ks73ad7816e7a61b3a/events?startDate=2015-06-01&endDate=2015-06-05',
    function(xhr) {
        var data = JSON.parse(xhr.responseText);
        alert('Successfully Received: '   JSON.stringify(data));
    },
    function(xhr) {
        var data = JSON.parse(xhr.responseText);
        alert('Request failed with code '  xhr.status  ': '   JSON.stringify(data));
    }
);

When I try to run the program per node I get this terminal output:

PS C:\Users\...\Documents\GitHub\teamup-test> node team-up-test.js
C:\Users\...\Documents\GitHub\teamup-test\team-up-test.js:45
        if (xhr.target.status < 400) {
                ^

TypeError: Cannot read properties of undefined (reading 'target')
    at exports.XMLHttpRequest.xhr.onload (C:\Users\...\Documents\GitHub\teamup-test\team-up-test.js:45:17)
    at exports.XMLHttpRequest.dispatchEvent (C:\Users\...\Documents\GitHub\teamup-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:591:25)
    at setState (C:\Users\...\Documents\GitHub\teamup-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:614:14)
    at IncomingMessage.<anonymous> (C:\Users\...\Documents\GitHub\teamup-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:447:13)
    at IncomingMessage.emit (node:events:539:35)
    at endReadableNT (node:internal/streams/readable:1345:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

So it seems like the program cannot read xhr.target.status, but why?

Summarized: I want to fetch calendar event data from my calendar on team-up per JS and display that data on a discord bot.

I am wondering if I even do need CORS since it's only for browsers. Hoping someone could guide me into the right direction please.

CodePudding user response:

The code tutorial here: https://apidocs.teamup.com/#querying-the-api-via-javascript--cors is to be executed in the browser, in the client. I don't think it can be used in the server. Remember, Node.js is a back-end language, it runs on the server, not on the browser.

You can make an API call in Node.js with the code below, but you should study Axios later

const https = require('https');

const options = {
    hostname: 'api.teamup.com',    
    path: '/ks73ad7816e7a61b3a/events?startDate=2015-06-01&endDate=2015-06-05',
    headers: {
        "Teamup-Token" : "API_KEY"
    },
  };

https.get(options, (resp) => {

  let data = '';    

  resp.on('data', (receivedDataBuffer) => {
    data  = receivedDataBuffer;    
  });

  resp.on('end', () => {    
        let receivedDataAsJSON = JSON.parse(data);

        //do what you need with the json    
  });

}).on("error", (err) => {
        console.log("Error: "   err.message);
    });
  • Related