I would like to give the contents of the local file in the server created by Express as data when generating the template object of the front-end Vue.js.
The only string would do well, but the file you want is in markdown format and contains many line breaks and backquotes.
Therefore, if you deploy a template in a client-driven javascript, the string ends with the backquote that exists in the middle, and you cannot pass it well.
The express routing is as follows:
router.get('/',(req,res,next)=>{
const str =fs.readFileSync(filepath).toString().replace('`','\`');
res.render('md', {data:obj});
});
Also, the ejs on the front side are as follows:
<script src='https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.js'></script>
<script>
window.onload=()=>{
new Vue({
el: '#editor',
data: {
input: `<%=data%>`
},
filters: {
marked: marked,
},
});
};
</script>
</head>
<body>
...
Checkers such as chrome found that the backquote of the data string deployed in <%=%> ended the string and no further characters were captured successfully.
I also wondered if res.locals can be used in client js by having a value, but it seems that it cannot be shared because client js has undefined.
Is there a way to pass the contents of the data generated by the server to the Vue object?
node.js vue.js
Is it correct that data is a string?In that case, you can use JSON.stringify
to pass the string into a JSON expression.
This is how you convert the string to a JSON expression during routing.
res.render('md', {data:JSON.stringify(obj)});
Front-side scripts use the JSON represented string as a string literal.
data:{
input: <%-data%>
},
By using JSON.stringify
, even strings containing backquotes and line breaks can be properly escaped and represented as JSON-expressed strings.The string represented by JSON is also valid as a JavaScript string literal (*), so you can embed it as a JavaScript code into the front-side script.
ただし However, older browsers will get errors if the original string contains U+2028 or U+2029 (Reference).I don't think a normal markdown template will mix that, but I think you should be careful to remove user input in advance.
The above method had a problem with JavaScript code termination if </script>
was included in the string.The workaround is to have EJS escape the JSON expression string into the script element attribute and retrieve it from the script side.
res.render('md', {data:obj});
<script data-input="<%=data%>">
window.onload=()=>{
new Vue({
el: '#editor',
data: {
input: document.currentScript.dataset.input
},
filters: {
marked: marked,
},
});
};
</script>
In this sample, the client-side attributes were retrieved in document.currentScript.dataset.input
, but this does not seem to work with IE11, so if IE11 support is required, add the ID to the script element.
© 2024 OneMinuteCode. All rights reserved.