Node.js passing parameters to client via express render

后端 未结 4 429
温柔的废话
温柔的废话 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:11

    Passing data list from node js to html

    server.js

    var http = require('http');
    var express = require('express');
    var sqlite3 = require('sqlite3').verbose();
    var bodyParser = require('body-parser');
    var path    = require("path");
    
    console.log('Server running at http://127.0.0.1:8081/');
    
    var __dirname = "D:/html-files";
    var app = express();
    var urlencodedParser = bodyParser.urlencoded({ extended: false })
    
    var engine = require('consolidate');
    
    app.engine('html', engine.mustache);
    app.use(express.static('./'));
    
    app.get('/', function(req, res) {
    
        res.render('index.html');   
    
    });
    
    app.post('/', function (req, res) {
       console.log("Got a POST request for the homepage");
       res.send('Hello POST');
    });
    
    app.post('/get-user-list', urlencodedParser, function (req, res) {
    
        let db = new sqlite3.Database('user.db', sqlite3.OPEN_READWRITE, (err) => {
            if (err) {
                console.error(err.message);
            }
            console.log('Connected to the user database.');
            console.log("ID" + "\t" + "NAME" + "\t" + "EMAIL");
        });
    
        db.serialize(() => {     
    
            var dataList = "";
    
            db.each('SELECT id, name, email FROM USER ', (err, row) => {
                if (err) {
                    console.error(err.message);
                }
                if(dataList != "")
                dataList = dataList + ',';
    
                dataList = dataList + '{"id":"' + row.ID + '","name":"' + row.NAME + '","email":"' + row.EMAIL + '"}';
                console.log("dataList : " + dataList);
            });
    
            db.close((err) => {
                if (err) {
                    console.error(err.message);
                }
                console.log('Close the database connection.');
                response = {'username':dataList};                           
                aFunction(res, dataList);
    
            });
    
        });
    
    });
    
    var aFunction = function(res, dataList) {
        console.log('return to page.');
        console.log("dataList : " + dataList);
        res.render(__dirname + "/list-all-users.html", response);
    };
    
    app.listen(8081, '127.0.0.1')
    
    0 讨论(0)
  • 2020-12-03 12:16

    The variable name you sent to the render function is only available while rendering the page, after it is sent to the client, it is not accessible. You have to use it in your view on the rendering stage.

    Since you are using handlebars, you can display it in your page like this, for instance:

    <h1>{{ name }}</h1>
    

    If you want to use this data in a javascript, use it inside a script tag:

    <script>
      var name = "{{ name }}";
      console.log(name);
    </script>
    
    0 讨论(0)
  • 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" });
    });
    
    0 讨论(0)
  • 2020-12-03 12:18

    If you want to get parameters on the clientside via javascript, you should do template like this <script>var data = data</script>, otherwise variables aren't available

    If you use Jade, it will be something like this:

    script(type='text/javascript').
        var name = !{name}
    
    0 讨论(0)
提交回复
热议问题