Node.js passing parameters to client via express render

后端 未结 4 439
温柔的废话
温柔的废话 2020-12-03 11:49

I\'m using Node.js and I\'m having issues communicating with a client.

I define Express:

var express             = require(\"express\");
var app              


        
4条回答
  •  情话喂你
    2020-12-03 12:16

    You are basically telling express to render your index page and providing a value for the name variable, but that doesn't necessarily make the name var available in your client side javascript. You need to edit your index template to display the name variable in the page. The syntax varies depending on the templating engine you are using (jade, ejs, dustjs).

    Another solution is to use an ajax call in your client page's javascript and use res.json on the server instead to send the data. Then you can evaluate name in the console. Ex using jquery:

    index.html:

    $.get( "/getvar", function( data ) {
      name = data.name;
    });
    

    server.js:

    app.get("/getvar", function(req, res){
        res.json({ name: "example" });
    });
    

提交回复
热议问题