Xi Xiao
Xi Xiao

Reputation: 973

pass object to javascript in ExpressJS

I have problem to convert back json string containing double quote to javascript object in JSON.parse(). Here is details below.

  1. I have a object saved in variable groupdatain nodejs app.js

    [{"_id":"56adb85319dec52455d11c21","fullName":"NY Metro Office 365 What New\" group","createdAt":"2015-08-25T17:03:59.000Z","stats":{"members":65}}]

  2. In my nodejs app.js code, groupdata object is passed to client as a json string.

    function doRender() { res.render('groupdata', { 'groupdata': JSON.stringify(groupdata) }); }

  3. My client code tries to prevent XSS attack first by function htmlDecode() then JSON.parse() a valid json string to object.

JSON.parse(test1) will succeed if only the string does not contain double quote. JSON.parse(test2) will fail as error below

     function htmlDecode(input){  //prevent XSS attack;
         var e = document.createElement('div');
         e.innerHTML = input;
         return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
     }
     console.log('groupdata: ' + "<%= groupdata %>");
     var test1 = htmlDecode("<%= (groupdata) %>");
     console.log('test1: ' + test1);
     var test2 = htmlDecode("<%= JSON.stringify(groupdata) %>");
     console.log('test2: ' + test2);
     JSON.parse(test1);  // Succeed if only test1 value contains no double quote
     JSON.parse(test2);  // ERROR: Uncaught SyntaxError: Unexpected token _

The console log in client chrome browser:

groupdata: [{&#34;_id&#34;:&#34;56adb85319dec52455d11c21&#34;,&#34;fullName&#34;:&#34;NY Metro Office 365 What New&#34; group&#34;,&#34;createdAt&#34;:&#34;2015-08-25T17:03:59.000Z&#34;,&#34;stats&#34;:{&#34;members&#34;:65}}]
test1: [{"_id":"56adb85319dec52455d11c21","fullName":"NY Metro Office 365 What New" group","createdAt":"2015-08-25T17:03:59.000Z","stats":{"members":65}}]
test2: "[{"_id":"56adb85319dec52455d11c21","fullName":"NY Metro Office 365 What New\" group","createdAt":"2015-08-25T17:03:59.000Z","stats":{"members":65}}]"

Question: How can I convert json string with double quote to javascript object in this case?

Upvotes: 1

Views: 1838

Answers (1)

Xi Xiao
Xi Xiao

Reputation: 973

It turns out that EJS has its own way to htmlescape to protect from XSS attack

    <script type="text/javascript">
     var groupdata = <%- JSON.stringify(groupdata); %>
    </script>

This is simple and clean. Thanks to @migg again for his commenting.

Upvotes: 2

Related Questions