[英]How to pass xml2js response to variable within node.js route?
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. 我正在使用带有node.js的xml2js从API检索数据,但是我只希望代码在激活“ / testpage”路由时运行,然后将api响应分配给变量并将其传递给testpage.ejs上的脚本,最终目的是将对象/变量内容打印到控制台。
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. 如果我将代码放在路由之外,则将响应分配给一个变量,然后将该变量传递给testpage脚本,那么它将正常工作。
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? 关于我在做什么错的任何想法吗?
You need to render your page after the response from API call is received. 收到API调用的响应后,您需要呈现页面。 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;
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.