Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS Pass variables to JavaScript

I am completely lost on this; I am using NodeJS to fetch a JSON and I need to pass the variable to my page and have JavaScript use the data.

app.get('/test', function(req, res) {
    res.render('testPage', {
        myVar: 'My Data'
    });

That is my Express code (very simple for testing purposes); now using JADE I want to gather this data which I know to render on the page is simply

p= myVar

But I need to be able to gather this data in JavaScript (if possible within a .js file) but for now just to display the variable in an Alert box I have tried

alert(#{myVar})

And many others if anyone can help be much appreciated

like image 718
Nick White Avatar asked Feb 13 '12 22:02

Nick White


People also ask

How do you pass arguments to middleware?

A standard middleware function always follows a signature with the three arguments (req, res, next) where req is the incoming request, res the response to be sent and next a reference to a function for stepping to the next middleware function.

What does Express next () do?

The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects.


2 Answers

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)}')
like image 183
dzajdband Avatar answered Oct 09 '22 13:10

dzajdband


As Timothy said:

<script type="text/javascript"> var myVar = #{JSON.stringify(myVar)}; </script>

This can also be done as follows in if you don't like to write HTML in Jade/Pug templates:

script
  var myVar = !{JSON.stringify(myVar)};
  var myVar2 = !{JSON.stringify(myVar2)};

Update: For Express 4 and Pug use script. instead of script so that it will be rendered as javascript instead of html.

like image 41
Bennit Avatar answered Oct 09 '22 12:10

Bennit