Reputation: 333
I'm new to Node.js/Express/Frontend development in general, and I'm trying to understand how to better process data being passed from a controller to a pug view which will then be processed by some JavaScript.
Right now, here's how I'm processing the data:
objectController.js:
exports.objectDetails = function (req, res) {
object.findById(req.params.id)
.then(results => {
res.render('layout', { data: results });
})
.catch(error => {
// error
})
};
layout.pug:
doctype html
html(lang='en')
head
script(src='frontend.js')
script(type='text/javascript').
var myObject = !{JSON.stringify(data)}
frontend.js:
"use strict";
someFunction(myObject);
Is this best practice or are there better ways of doing this?
I've tried looking at multiple sources and this is the best one I could find.
Thanks in advance.
Upvotes: 1
Views: 486
Reputation: 4164
The way you've done now currently works so the question is a bit vague, but if you want a standard / more idiomatic approach then I'd suggest making a HTTP call from your frontend JS to get your graph data which you can then map. That would mean your server side code to serve up the main page will just render the pug template and send back the HTML, CSS, and JS. Your frontend JS will then hit an endpoint specifically designed to retrieve the graph data.
You might also find this gives a better user experience by allowing the page to load in the browser quickly and any longer data crunching processes to take place afterwards.
So you'd end up with 2 HTTP calls and 2 endpoints for them. The first would render the pug template without any graph data. The second will generate the graph data and send it back in a JSON format for you to pass into your graphing library.
Upvotes: 1