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 hidden or 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 hidden or 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> |
@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
Here's how I did it for an array:
Backend
Frontend
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 thenJSON.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).