I want to pass a variable from Node.js to the internal JavaScript that is inside "flashcards", I am trying to use EJS to pass the array "cardNames"
Server side:
app.get("/apps/flashcards", (req, res) => {
res.render("flashcards", { cardNames: ["card1", "card2", "card3", "card4"] });
})
In my "flashcards" EJS file I have four span elements, all of which have the same class ("my-cards"). I want to change their textContent as shown below:
Client side (flashcards file):
<script>
const cardNames = <% cardNames %>
const cards= document.querySelectorAll(".my-cards");
for (let i = 0; i < cards.length; i++) {
cards[i].textContent = cardNames[i] + ", Score: 0";
}
</script>
I get an error:
"Uncaught SyntaxError: Unexpected token ‘const’"
How can I send a file from Node.js to the internal or even external JavaScript? The logic MUST be separate from the html elements so it doesn’t get confusing.
It doesn’t have to be EJS, I’m willing to use other methods as long as I can achieve results.
3
Answers
you first get the variables and then simply pass then like this
and also you got the error coz you are accessing it in wrong way, as when this variable is reaching in ejs it will be in string so first convert that variable to array first like this
const cardNames = <% cardNames %>.trim().split(",")
To pass a variable from Node.js to JavaScript, you can do so by embedding the JavaScript code within your Node.js script or by using a Node.js library like vm (Virtual Machine) or node-ipc (Inter-Process Communication).
try