Last active
January 4, 2021 16:39
-
-
Save danschumann/ae0b5bdcf2e1cd1f4b61 to your computer and use it in GitHub Desktop.
How to pass an object from nodejs to frontend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
myObject = { ... } | |
this.injectString = JSON.stringify( myObject ).replace(/\\/g, '\\\\').replace(/"/g, '\\\"') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
We only worry about parsing now, since everything should have been properly escaped | |
<script> | |
window.myObjectFrontend = JSON.parse("<%- @injectString %>"); | |
</script> |
Here's how I did it for an array:
Backend
const response = await request(GRAPHQL_ENDPOINT, query)
return res.render('research/index', {
articles: JSON.stringify(response.getAllArticles) || [] // Stringify output to Frontend
})
Frontend
<script>
window.quillContent = <%- articles.replace(/=>/g, '=>') %> // I had to fix => back to fat arrow
</script>
<% const allArticles = JSON.parse(articles)
allArticles.forEach((article, i) => { %>
<div id="editor<%- i %>"></div> // Create dynamic number of divs
<% }) %>
<script>
'use strict'
hljs.configure({
languages: ['javascript']
})
window.quillContent.forEach((article, i) => {
const quill = new Quill(`#editor${i}`, { // Create dynamic number of Quill Editors
modules: {
syntax: true,
toolbar: false
},
readOnly: true,
theme: 'snow'
})
quill.setContents(JSON.parse(window.quillContent[i].content)) // Parse input from Backend
})
</script>
This code is specific to Quill when using syntax highlighting on ES6 code, but it demonstrates iterating through the array in a common manner.
The basics are the same: JSON.stringify()
Array output to Frontend, and then JSON.parse()
the Array in the Frontend when you consume it, and you may see some HTML entities get leaked in (which is feeling like an EJS templating engine issue).
@if(isset($payload))
{{--*/
$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
/*--}}
<script>
window.__payload = JSON.parse("{!!$payload!!}");
</script>
@endif
Here's a php blade version. Payload is any object.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We replace
\
with\\
and"
with\"
so that it can be 1 string when it is printed in htmlWe are replacing because it needs to be passed to frontend through
JSON.parse("{{injectString}}");
( note the"
wrapping the backend string )."{"mykey":"my\"val"}"
-- pre-regex -- not parseable, the frontend sees this as 4 strings with junk in between"{\"mykey\":\"my\\\"val\"}"
-- post-regex -- parseablethe first replace is for
my\"val
, since the second replace would cause that to break. If only the second replace was applied, it would becomemy\\"val
means it escapes a slash, and the double quotes would end the parse string prematurely. Applying both regexes makes itmy\\\"val
, the first two slashes make one slash, and the third escapes the"
, making it identical tomy\"val
when printed