Reputation: 15
<script>
window.data = <%- JSON.stringify(data) -%>
</script>
<%- include('header') -%>
<div id="root"><%- content -%></div>
<%- include('footer') -%>
This throws an error saying unexpected end of input in the script tag. This is running on the server side and both data and content is provided by the render call.
Upvotes: 0
Views: 390
Reputation: 131
This is what works for me.
1st option, turn object/array into string on server, send to EJS, and then parse it on the client-side while replacing some special characters:
Server:
res.render('/', {
data: JSON.stringify(data)
});
Client:
const data = "<%= data %>";
const dataObject = JSON.parse(data.replace(/"/gi, '\"'));
2nd option, send the object/array as-is from server to client. Use template literals on the client-side to stringify, and then JSON.parse:
Server:
res.render('/', {
data: data
});
Client:
const data = `<%- JSON.stringify(data) %>`;
const dataObject = JSON.parse(data);
Upvotes: 0
Reputation: 713
This means that the function call JSON.stringify
ran into an error. Could you log out the data and verify that it is indeed valid JSON?
Some common faults are missing brackets like }
or ]
, or keys/values in the JSON that are not wrapped with double quotes ("
).
Upvotes: 1