Page 1 of 1

api call with https

Posted: Sat Jan 16, 2021 10:00 am
by foxpalace
Hello,
whats wrong with this script, when I execute the Script with nodjs on Terminal it works, when I transpile it, the api-call will never run in Switch????

Code: Select all

const https = import('https');

async function jobArrived(s: Switch, flowElement: FlowElement, job: Job) {

    let datei = job.getName();
    let zielpfad = await flowElement.getPropertyStringValue("ZielPfad");
    var splittArray = datei.split("_");
    var jahrArray = splittArray[3].split(".");
    var jahr = 20 + jahrArray[0];
    var suffix = jahrArray[1];
    var objekt = splittArray[0];
    var kw = splittArray[2];

    await job.log(LogLevel.Info, "Jahr: " + jahr);
    await job.log(LogLevel.Info, "Suffix: " + suffix);
    await job.log(LogLevel.Info, "Objekt: " + objekt);
    await job.log(LogLevel.Info, "KW: " + kw);
    await job.log(LogLevel.Info, "ZielPfad: " + zielpfad);

    var url = 'https://url.com/api/v1/titles/' + objekt;
    await job.log(LogLevel.Info, "URL: " + url);

    (await https).get(url, (res) => {
        let body = "";

        res.on('data', (chunk) => {
            body += chunk;
        });

        res.on("end", () => {
            try {
                let json = JSON.parse(body);
                var verladsid = json.pub_publisher_id;
            } catch (error) {
                job.log(LogLevel.Info, "BLA");
            };
        });
    }).on("error", (error) => {
        job.log(LogLevel.Info, "BLA");
    });
}


When I try
https.get ... whitout await Visual Studio marks it as error

Regards Michael

Re: api call with https

Posted: Mon Jan 18, 2021 9:02 am
by freddyp
Same remark as for this post (viewtopic.php?f=26&t=3849): use Promises!

A word of advice for working with HTTP calls: use the axios package. It is easy to use and highly configurable.

Code: Select all

const axios = require("axios"); //JavaScript
import axios from "axios";  //TypeScript

...

    try {
      let result = await axios({method:"get", url:"https://url.com/api/v1/titles/" + objekt});
      //do something with the result
    } catch(error) {
      //do something with the error
    }

For more options and examples, see the axios documentation. When using the examples you find, always make sure not to use the .then callback functions. Remove them and await the axios call. It is as simple as that.

Re: api call with https

Posted: Mon Jan 18, 2021 12:52 pm
by foxpalace
Hi Freddy,
you made my day :)
I have to learn, to learn, to learn ...

Greetings Michael