[英]Express.js render data from external API
I have a function to get data from an external API: 我有一个从外部API获取数据的功能:
app.get("/getdata", (req, res) => {
request.get({
url: 'http://externalurl',
json: true
})
.pipe(res);
});
It just shows the received JSON object in a browser. 它只是在浏览器中显示接收到的JSON对象。 The question is, how could I render this data in a template like it's usually done with express methods like
res.render("template", {data:data})
so that I could format it? 问题是,我该如何像使用
res.render("template", {data:data})
这样的快速方法那样在模板中呈现此数据,以便对其进行格式化?
Assuming your request
variable comes from the request npm package , you can use a callback function to receive the response data: 假设您的
request
变量来自request npm包 ,则可以使用回调函数来接收响应数据:
app.get("/getdata", (req, res, next) => {
request.get("http://externalurl", (err, response, body) => {
if (err) {
return next(err);
}
res.render("template", {data: JSON.parse(body)});
});
});
Alternatively, if you're not comfortable with using calllbacks, you can either wrap the request
call in a promise or use a ready-made wrapper (please refer to the package's readme for recommendations). 另外,如果您对使用回调不满意,则可以将
request
调用包装在Promise中,也可以使用现成的包装器(请参考程序包的自述文件以获取建议)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.