如何将异步输出提供给express渲染器?

rfbsl7qr  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(344)

我请求获取一个示例xml文件,对其进行解析,现在我想将其传递给ExpressRenderer,以便在页面上动态显示该值。我的路由器:

app.get('/dynamic_view', function(req, res){
    res.render('dynamic', {
        name: //pass my output here
    });
 });

我的异步输出如下所示:

const parseString = require('xml2js').parseString;
const axios = require('axios');

let url = 'https://www.w3schools.com/xml/simple.xml';

    axios.get(url)
      .then(response => {
        parseString(response.data, function (err, result) {
          console.log(result.breakfast_menu.food[0].name); // returns 'Belgian Waffles'
        });        
      })

如何将异步变量输出(应该是“比利时华夫饼”)传递给 name 性质 res.renderer ?

deyfvvtc

deyfvvtc1#

const parseString = require('xml2js').parseString;
const axios = require('axios');

let url = 'https://www.w3schools.com/xml/simple.xml';

app.get('/dynamic_view', function(req, res, next){
    axios.get(url)
      .then(response => {
        parseString(response.data, function (err, result) {
          if (err) return next(err)
          res.render('dynamic', {
            name: result.breakfast_menu.food[0].name
          });
        });        
      })
 });

相关问题