Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an object to client in node/express + ejs?

I have a pretty large object that I need to pass to a function in a client script. I have tried using JSON.stringify, but have run into a few issues with this approach - mostly performance related. Is it possible to do something like this in ejs?

app.get('/load', function(req, res) {     var data = {         layout:'interview/load',         locals: {             interview: '',             data: someLargeObj         }     };     res.render('load', data); }); 

And in my client script, I would pass this object to a function like so

<script type="text/javascript">     load(<%- data %>); // load is a function in a client script </script> 

When I try this I get either

<script type="text/javascript">     load(); </script> 

or

<script type="text/javascript">     load([Object object]); </script> 
like image 351
Errol Fitzgerald Avatar asked Jun 22 '12 07:06

Errol Fitzgerald


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. }

Is EJS client side?

Sure, EJS works on the client. You can trivially keep the template in a string variable or apply EJS to user-provided input, but more likely, you'll want to store a template in a script (which can be in an external file) or use fetch to grab your template from another file on demand.


1 Answers

In Node.js:

res.render('mytemplate', {data: myobject});

In EJS:

<script type='text/javascript'>   var rows =<%-JSON.stringify(data)%> </script> 

SECURITY NOTE : Don't use this to render an object with user-supplied data. It would be possible for someone like Little Bobby Tables to include a substring that breaks the JSON string and starts an executable tag or somesuch. For instance, in Node.js this looks pretty innocent...

var data = {"color": client.favorite_color} 

but could result in a client-provided script being executed in user's browsers if they enter a color such as:

"titanium </script><script>alert('pwnd!')</script> oxide" 

If you need to include user-provided content, please see https://stackoverflow.com/a/37920555/645715 for a better answer using Base64 encoding

like image 171
prototype Avatar answered Sep 24 '22 02:09

prototype