Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variable on client-side from the server-side (express.js, node.js)

Server-side:

app.get('/auth', function(req, res) {
    res.render('auth.jade', {
        variable: true
    });
});

How to get variable 'variable' on client-side from the server side?

I tried:

alert(variable);
like image 496
owl Avatar asked Mar 19 '23 21:03

owl


1 Answers

You can't get server-side variable in a node application in client-side javascript in a browser window directly. Although they support the same programming language, they're just two different runtimes.

your question is about how client side javascript can communicate server-side resources like /auth. options are:

Provide your data in script tag on your web page rendered by jade template. for example:

html(lang="en")
  head
    title= pageTitle
  script(type='text/javascript').
    var generatedData = {variable:true}
body

Then you can use alert(generatedData) to get it. notice that the data has to be serializable data without any function or reference.

Usually people use JSON which means you need to write some client side code to communicate with server-side resource. like using jQuery in client side:

$.get('/auth').done(function(data){ alert(data); });

With server-side code where it sends data in JSON by express response object automatically:

app.get('/auth', function(req, res) {
    res.send({
        variable: true
    });
});
like image 192
shawnzhu Avatar answered Apr 24 '23 19:04

shawnzhu