简体   繁体   中英

How do I get data from server route to javascript? Nodejs Express pug

I am pretty new at this so I hope i'm asking the right question, and approaching this the right way. I am trying to get data from the server. I have successfully passed it through a route to a pug page, but the javascript on that page does not have access to these objects. Here is the server code. Also posted is the client side javascript where I don't have access to the objects passed to the pug page.

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

  var s = req.user.stocks;
  var t = [];

  // get array of stock symbols
  for(var stock in s)
    {
      if (isNaN(parseInt(stock)))
      {    
      }
      else
      {
        s.push(req.user.stocks[stock].symbol);
      }
    }

  //pull historic data from yahoo-finance
  yahooFinance.historical({
    symbols: ['AAPL','YHOO'],
    from: '2012-01-01',
    to: '2012-02-28',
    period: 'd'  // 'd' (daily), 'w' (weekly), 'm' (monthly), 'v' (dividends only) 
  }, function (err, quotes) {

    if(err){
      // do nothing
    }else{
      res.render('stockView', {title: 'Stock View', user: req.user, stocks: quotes, mystocks: s, tickers: t });
    }

  });

});


// *********javascript code in stockView.pug file****************
script(type='text/javascript').
      $(function(){
        var tickers = #{title};

It doesn't work like that, Pug allows you to only handle the view and hence it directly renders the html view there. Pug Can only render views (HTML), It won't be able to give the javascript there access to the variables available to pug.

You can use Ajax or Socket.io instead so your javascript code on the client side is connected with the javascript code you write on the server-side.

That's Why we've technologies like socket.io and ajax, they allow the client side to be in touch with the backend and with Node I prefer to use Socket.io.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM