Search code examples
javascriptnode.jslocals

How to access res.locals from script instead of html


I can print my res.locals.myData like this on client side: <%= myData%>

How can I use it within script? This doesn't work:

<script type="text/javascript">
var receivedData = myData
</script>

EDIT Server output using res.locals.myData:

[ '83',
  { v: 294,
    f: '29 <img src="img/Gold.png">  <img src="img/Silver.png"> 94 <img src="img/Copper.png">' },
  { v: 210,
    f: '21 <img src="img/Gold.png">  <img src="img/Silver.png"> 10 <img src="img/Copper.png">' },
  { v: 1.38 } ]

Using console.log(<%= sendTableData%>) The code is rendered as follows:

console.log(83,[object Object],[object Object],[object Object])

Which gives the

Unexpected identifier 'Object'

error

EDIT2 Another approach I've tried is using JSON.stringify and JSON.parse however something happens to the string when send using res.locals. Small piece of the string: ["83",{"v":294,"f":"29 is this when it arrives: &#34;83&#34;,{&#34;v&#34;:294,&#34;f&#34;:&#34;29. It changes the quotation marks? Anyway I would rather avoid this method and send it as it's original data.

Edit3 Solution was to use <%- myData%> client side (notice - instead of =) after sending data as a string.


Solution

  • Use the following client side:

    res.locals.myData = JSON.stringify(myData)
    

    And the following client side:

    var tableData = <%- myData%>; // For .ejs
    var tableData = !{myData} // For .jade (I think)