繁体   English   中英

如何将xml2js响应传递给node.js路由内的变量?

[英]How to pass xml2js response to variable within node.js route?

我正在使用带有node.js的xml2js从API检索数据,但是我只希望代码在激活“ / testpage”路由时运行,然后将api响应分配给变量并将其传递给testpage.ejs上的脚本,最终目的是将对象/变量内容打印到控制台。

我面临的问题是我得到了上面代码的“未定义”浏览器控制台响应。

如果我将代码放在路由之外,则将响应分配给一个变量,然后将该变量传递给testpage脚本,那么它将正常工作。

在这一点上,我假设这可能是一个异步问题,但我不确定,甚至不确定如何解决。

// 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>

关于我在做什么错的任何想法吗?

收到API调用的响应后,您需要呈现页面。 像这样更改代码:

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;
        }
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM