将变量从 Express 传递到客户端 JavaScript

Pass variable from Express to Client JavaScript

最终,我试图从节点服务器传递 JSON 数据,以供客户端中的 D3 使用。

这是我的 index.js

var express = require('express');
var router = express.Router();

var portmix = require('../data/holdings.json');

/* GET individual portfolio page. */
router.get('/portfolio/:portcode', function(req, res) {

  var porthold = [];
  for(var i in portmix){
    if(portmix[i].PortfolioBaseCode === req.params.portcode){
        porthold.push(portmix[i])
  }}

  res.render('index', { 
    pagetype: 'single_portfolio',
    holdings: porthold[0]
  });
});

module.exports = router;

这是 ejs 文件:

<div class="portfolio">

    <h2><%= holdings.ReportHeading1 %></h2>
    <ul>
        <li>Cash: <%= holdings.CashMV %></li>
        <li>Fixed Income: <%= holdings.FixedMV %></li>
        <li>Equity: <%= holdings.EquityMV %></li>
        <li>Alternatives: <%= holdings.AltMV %></li>
    </ul>

    <div class="chart">
    </div>
</div> 

它可以显示 "holdings" 值。但是,如果我尝试使用以下方法从客户端 js 调用它:

console.log("Holdings: " + holdings);

结果是

Holdings: undefined

有办法吗?还是我做错了?

不能在客户端调用EJS变量,必须把JSON输出到页面,然后去取

<script type="text/javascript">

   var json_data = <%- JSON.stringify( holdings ); %>

   // use the above variable in D3

</script>

<div class="portfolio">

    <h2><%= holdings.ReportHeading1 %></h2>
    <ul>
        <li>Cash: <%= holdings.CashMV %></li>
        <li>Fixed Income: <%= holdings.FixedMV %></li>
        <li>Equity: <%= holdings.EquityMV %></li>
        <li>Alternatives: <%= holdings.AltMV %></li>
    </ul>

    <div class="chart">
    </div>
</div>