Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing objects to client in node + express + jade?

I have a pretty heavyweight query on the server that results in a new page render, and I'd like to pass along some of the results of the query to the client (as a javascript array of objects). This is basically so I don't have to do a separate JSON query later to get the same content (which is mostly static). The data will be useful eventually, but not initially so I didn't put it directly into the document.

app.get('/expensiveCall', function(req, res) {     // do expensive call     var data = veryExpensiveFunction();     res.render('expensiveCall.jade', {         locals: {                 data: data,                 }         });     }); }); 

data is a array of objects and only some are initially used. I'd like to pass either the entirety of data over or some subsets (depending on the situation). My jade looks like normal jade, but I would like to include something like

<script type="text/javascript"> var data = #{data}; </script> 

but this doesn't work (it's an array of objects).

like image 240
killermonkeys Avatar asked Oct 07 '11 00:10

killermonkeys


People also ask

How do you pass an object in node JS?

How to pass an object to another function in Node. js. Here's a working example of that function passing technique: var http = require('http'); function OnRequest(request, response) { sendPage(request, response); //This is where the request and response objects are passed as parameters. }

Which method is used to send the data from Nodejs server to client?

Methods to send response from server to client are: Using send() function. Using json() function.

What is Express () in node JS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.

What do the request and response objects in Express represent?

The req object represents the HTTP request and has properties for the request query string, parameters, body, and HTTP headers. The res object represents the HTTP response that an Express app sends when it gets an HTTP request.


1 Answers

You can't inline a JS object like that, but you can JSON.stringify it before:

<script type="text/javascript">   var data = !{JSON.stringify(data)}; </script> 
like image 128
Adrien Avatar answered Oct 06 '22 20:10

Adrien