0

I'm using xml2js with node.js to retrieve data from an API, but I would only like the code to run when the "/testpage" route is activated, which would then assign the api response to a variable and pass it along to a script on testpage.ejs where the end goal is to print the object/variable contents to the console.

The problem I'm facing is that I'm getting the "undefined" browser console response with the above code.

If I place the code outside of the route, have the response assigned to a variable and then pass that variable to the testpage script, then it works fine.

At this point I'm assuming it could be an asynchronous issue, but I'm not sure, or even how to tackle it if so.

// Node.js
const requestPromise = require('request-promise'),
  xml2js = require('xml2js').parseString,
  express = require("express"),
  app = express();

const port = 3200,
  apiURL = 'https://api.exampleapi.com';

app.set("view engine", "ejs");

app.use('/public', express.static(__dirname + "/public"));

app.get("/testpage", function(req, res){

var myApiObject; // To store api response

requestPromise.post(apiURL, (error, response, body) => {
if(error){
    console.log(error);
    return error;
}
}).then( (body) => {
    xml2js(body, (err, result) => {

        if(err){
            console.log(err);

        } else {

            myApiObject = result;
            return result;
        }
    });
});

res.render("testpage", {myApiObject: myApiObject});
});


app.listen(process.env.PORT || port, function(){
console.log("Server is running...");
});

<!--testpage.ejs-->
<html>
    <head>

    <title>
    </title>

</head>

<body>

    <p>This is the testpage</p>

    <script>
        var myObj =<%-JSON.stringify(myApiObject)%>
        console.log(myObj);
    </script>

</body>

Any ideas on what I'm doing wrong?

1 Answer 1

1

You need to render your page after the response from API call is received. Change your code like this:

requestPromise.post(apiURL, (error, response, body) => {
if(error){
    console.log(error);
    return error;
}
}).then( (body) => {
    xml2js(body, (err, result) => {

        if(err){
            console.log(err);

        } else {
            res.render("testpage", {myApiObject: result});
            return result;
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.