Making External API Call in Script beforeRender Using Node http/https Module



  • Hello, I'm having trouble calling an API from a script. Using Node's built-in http or https module, I'd like to make a call to the api and return data to be passed to the JsReport request via a beforeRender function.

    I noticed that my response callback doesn't seem to be triggering as no logging occurs. The call for callApi doesn't seem to trigger the promise or rejection events? I've tried using an https.request as well as http.request (shown here).

    I have been able to perform this call with Postman and receive the proper response, now I'm just trying to translate it into JsReport.
    Any help would be appreciated!

    Thanks,
    Austin
    0_1647380145645_Screenshot 2022-03-15 173419.png



  • Also, I have checked and my template is set to run the script.



  • You have some basic coding bugs there mainly caused by mixing callbacks and promises. I recommend not using callbacks but instead just promises. It would make things easier for you.

    Remove the done parameter from the beforeRender and use async instead.
    Try axios or another promise-based library for making http calls.

    const axios = require('axios')
    async function beforeRender(req, res) {
        const r = await axios.get('http://localhost:5488/odata/templates')    
        req.data = { ...req.data, ...r.data}
    }
    


  • @jan_blaha
    That makes sense, thank you for the suggestion Jan. As of right now, the environment running JsReport at REDCap Cloud doesn't have the Axios module installed.
    On top of this, it's running an older version of JsReport prior to the NPM extension and I don't have access to manually installing modules onto their server. (Hence using the stock Node HTTP/HTTPS modules)

    I think I'll just have to put in a request to REDCap to have Axios installed onto their JsReport environment.
    Thanks,
    Austin



  • You can make it working also with http module. You just need to work properly with async promises and callbacks. See an example here

    https://playground.jsreport.net/w/admin/hG7mEoll


Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.