如何在 Node Js 和 Express js 中使用渲染更新已发送的数据

我试图随时从我的 router.js 发送数据以在 Javascript 中读取,但我不知道如何传递它而不必再次呈现页面。我希望在满足新坐标的条件时,更新页面上的数据而无需再次重新加载页面。


router.get('/', function (req, res) {


    dbC.db.collection('collection').where('id', '==', 'AnID')

      .onSnapshot(querySnapshot => {

        querySnapshot.docChanges().forEach(change => {

          if (change.type === 'added') {

            let coord = change.doc.data();

            console.log('--------------New coord--------------');

            res.header({ lat: coord.payload_fields.latitude_gps, lng: coord.payload_fields.longitude_gps });

          }

         });

      });

      res.render('index', { title: "FMCS", title2:"Tracing", active: {home: true, map: true},  lat: 0, lng: 0 });

    })



My hbs:

 

<script>

  var point = { lat: {{{lat}}}, lng: {{{lng}}} };

</script>


温温酱
浏览 111回答 1
1回答

哔哔one

如果你想在网页中实时更新数据,你应该在呈现的页面中使用 Firestore 而不是在 express 控制器中。首先在渲染的页面标题中添加 Firestore 依赖<script src="https://www.gstatic.com/firebasejs/7.21.1/firebase-app.js"></script><script src="https://www.gstatic.com/firebasejs/7.21.1/firebase-firestore.js"></script>其次在渲染页面中初始化Firestore并监听更新<script>&nbsp; firebase.initializeApp({&nbsp; &nbsp; apiKey: '### FIREBASE API KEY ###',&nbsp; &nbsp; authDomain: '### FIREBASE AUTH DOMAIN ###',&nbsp; &nbsp; projectId: '### CLOUD FIRESTORE PROJECT ID ###'&nbsp; });&nbsp; var db = firebase.firestore();&nbsp; dbC.db.collection('collection').where('id', '==', 'AnID')&nbsp; .onSnapshot(querySnapshot => {&nbsp; &nbsp; querySnapshot.docChanges().forEach(change => {&nbsp; &nbsp; &nbsp; if (change.type === 'added') {&nbsp; &nbsp; &nbsp; &nbsp; // use DOM API to update data location in the rendered page&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });&nbsp; })</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript