【问题标题】:Passing json data from mongodb query to javascript variable client side using express and node使用express和node将json数据从mongodb查询传递到javascript变量客户端
【发布时间】:2017-06-28 17:31:29
【问题描述】:

我在使用 express 将一些 json 数据从 mongodb 查询服务器端发送到 javascript 变量客户端时遇到问题。我正在使用 Mapbox Gl-Js,我需要使用来自 mongodb 服务器的一些 json 数据在页面上加载 geojson 行。 这是我的路线:

# /routes/index.js
var express = require('express');
var router = express.Router();
var db = require('../db');
/* GET home page. */
router.get('/', function(req, res, next) {
    var collection = db.get().collection('route');
    collection.find({ id : "route" }).toArray(function(err, docs){
        res.render('index', {
            "data" : docs
        });
    });
});
module.exports = router;

我知道这个查询在服务器端有效。现在,我需要将此 geojson 数据传递给客户端的 javascript 文件。可能值得一提的是,这个文件不是由路由器渲染的,而是 index.jade 文件被渲染,并且在其中引用了这个文件。

mapboxgl.accessToken = 'REDACTED';
# /public/map.js
// check if mapbox is supported on client's browser
if (!mapboxgl.supported()) {
  alert('Your browser is not supported. Please use a more modern browser.');
} else {
    var map = new mapboxgl.Map({
        container: 'map', // container id
        style: 'REDACTED', //stylesheet location
        center: [48.010062, 29.310335 ], // starting position
        zoom: 11 // starting zoom
    });
}
// make arabic text work
mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-
js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js');
// add navigation and geolocation controls
map.addControl(new mapboxgl.NavigationControl());
map.addControl(new mapboxgl.GeolocateControl());

var json_data = JSON.stringify(data)
console.log(json_data);

console.log 时间抛出 ReferenceError。我怎样才能解决这个问题?这与路由器没有直接呈现此页面有关吗?

【问题讨论】:

    标签: javascript node.js mongodb express mapbox-gl-js


    【解决方案1】:

    您尝试在 javascript 中访问 jade 模板数据的方式不正确。您可以在jade文件中声明变量,然后可以在js文件中使用它。例如

    index.jade

    script(type='text/javascript').                                                
       var json_data = JSON.stringify(data)
    script(src='/public/map.js')
    

    /public/map.js

    console.log(json_data);
    

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2017-08-26
      • 2012-06-18
      • 2018-11-02
      • 2016-09-18
      相关资源
      最近更新 更多