如何将对象从Express应用传递到Pug前端?

问题描述 投票:0回答:1

所以我在将数据从我的快速后端传递到哈巴狗前端时遇到了问题。我想呈现从数据库中提取的位置数据,将其传递到位置页面并遍历位置数据。浏览器无法识别数据。我在做什么错?

app.js

    app.get('/:store_id', async (req, res) => {
      await db.stores.findById(req.params.store_id)
        .then(locations => {

          // example of locations
          locations = [ 
          {
            location: 'Fremont',
            latitude: 37.49267,
            longitude: -121.94409
          },
          {
            location: 'Folsom',
            latitude: 38.64392,
            longitude: -121.18621
          }
        ];
        res.render('location', {locations})
      }).catch(error => res.render('landing'))
    })

location.pug

block content
    script.

        locations.forEach(function(sc) {
          // do something with sc
        }

"express": "^4.17.1",
"pug": "^2.0.4",
express pug
1个回答
0
投票

将在处理后的HTML文件中呈现为脚本块:

<script>
  locations.forEach(function(sc) {
      // ...
  }
</script>

它可能不会在页面加载时执行任何操作(除非您碰巧有一个可迭代的locations变量可用)。您想使用帕格的iteration syntax

content
  each location in location
    //- do stuff
© www.soinside.com 2019 - 2024. All rights reserved.