简体   繁体   中英

Node.js passing parameters to client via express render

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

I define Express:

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

When I try and pass a parameter to the client upon requesting a page the variable holds no data, for example:

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

On the index page, when I use the console to print the variable ( name )it returns "" .

More info: http://expressjs.com/api.html#app.render

Am I missing something or doing something wrong?

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>

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" });
});

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}

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM