Pass Variables to JavaScript in Expressjs

Pass variables to JavaScript in ExpressJS

You could use this (client-side):

<script>
var myVar = <%- JSON.stringify(myVar) %>;
</script>

You could also get EJS to render a .js file:

app.get('/test.js', function(req, res) {
res.set('Content-Type', 'application/javascript');
res.render('testPage', { myVar : ... });
});

However, the template file (testPage) would still need to have the .html extension, otherwise EJS won't find it (unless you tell Express otherwise).

As @ksloan points out in the comments: you do have to be careful what myVar contains. If it contains user-generated content, this may leave your site open for script injection attacks.

A possible solution to prevent this from happening:

<script>
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
var myVar = JSON.parse(htmlDecode("<%= JSON.stringify(myVar) %>"));
</script>

ExpressJS Pass variables to JavaScript

Try the following:

alert('!{myVar}')

It's a good idea to JSON encode the data if is more than just a string.

alert('!{JSON.stringify(myVar)}')

How to pass variables from client to Express api

to send an array of data to the Express app running on your server, the most simple way is to send it as an JSON object. A simple example using jQuery is shown below:

Client code:

    var your_calculated_array = []; // Set your calculated array here
$.ajax({
type: 'POST',
url: 'YOUR_EXPRESS_ENDPOINT',
data: { your_data: your_calculated_data },
dataType: 'json',
success: function (data) {
// Handle the response here
}
});

Server-side code (using body-parser middleware to parse json body):

.....

var bodyParser = require('body-parser')
app.use( bodyParser.json() );

app.post(YOUR_EXPRESS_ENDPOINT, function(req, res) {
var calculated_data = req.body.your_data
// ...
})

.....

Pass Parameter to Function Express JS

function rolesToken(role, req, res, next) is not a proper Express.js route handler, as you already know (and hence the question, I assume).

What you can do is to write your rolesToken as a function that returns the actual Express.js compliant handler (function):

function rolesToken(role) {
return function(req, res, next) {
var decoded = jwt.decode(req.token);
if (!decoded.permissions.includes(role)) {
res.json("sem permissao");
} else {
next();
}
};
}

Pass variable from Express to Client JavaScript

You can't call the EJS variables from the clientside, you have to output the JSON to the page, and then fetch it

<script type="text/javascript">

var json_data = <%- JSON.stringify( holdings ); %>

// use the above variable in D3

</script>

<div class="portfolio">

<h2><%= holdings.ReportHeading1 %></h2>
<ul>
<li>Cash: <%= holdings.CashMV %></li>
<li>Fixed Income: <%= holdings.FixedMV %></li>
<li>Equity: <%= holdings.EquityMV %></li>
<li>Alternatives: <%= holdings.AltMV %></li>
</ul>

<div class="chart">
</div>
</div>


Related Topics



Leave a reply



Submit