Marcin
Marcin

Reputation: 447

Express JS Passing variable to Javascript file

In my Express JS app, I am using ejs view engine, I want to pass variable to javascript file on client side.

This is my render:

return res.render('data/show', {
    data: data
});

This is working for me:

<script>
    var data = <%- JSON.stringify(data) %>;
    console.log(data);
</script>

But my function is in separate .js file that I am including, when I am using the same code:

function gettingData() {
    var data = <%- JSON.stringify(data) %>;
    console.log(data);
}

I am getting syntax error:

Uncaught SyntaxError: Unexpected token <

Thank you in advance for any suggestions.

Upvotes: 0

Views: 1801

Answers (2)

fh0592x
fh0592x

Reputation: 286

You could give this a shot...JSON.stringify(<%= data %>). Hope this helps :)

Upvotes: 0

kshetline
kshetline

Reputation: 13682

I haven't worked with EJS, but my guess would be that:

<%- JSON.stringify(data) %>

...only works as a substitution in the HTML files being served up by the node server (with an .ejs extension, I believe), but that the above would come straight through as-is in a separate .js file being loaded separately.

Upvotes: 1

Related Questions