【问题标题】:how to feed the async output to express renderer?如何将异步输出提供给表达渲染器?
【发布时间】:2021-09-19 03:17:08
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript node.js express asynchronous pug


    【解决方案1】:
    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
              });
            });        
          })
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 2016-05-02
      • 2021-05-19
      • 2016-02-28
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      相关资源
      最近更新 更多