Question

I'm currently experimenting with Node.js, and I'm stuck a little bit. I'm trying to pass a query to Mustache.

Index.js

//Load Express Framework

var express = require('express');

//Load Mustache Template Engine
var mustachex = require('mustachex');

//Load MySQL
var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'nodeuser',
    password : 'testpass',
    database : 'node',
});

connection.connect(function(err) {
});


//Call express
var app = express();

//Set Global App Settings
app.engine('html', mustachex.express);
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

//Call the layout
app.get('/', function(req, res) {
    var sql    = 'SELECT * FROM menu WHERE id = 1';
    connection.query(sql, function(err, results) {
    });
    for (var i in results){
         var sqlResult = results[i];
         console.log(sqlResult['address'], sqlResult['text']);
    }
    res.render('index');
});

//app.get('/test', function(req, res) {
//  res.render('test');
//});


//Create Server
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
    console.log("Listening on " + port);
});

Header.html (partial)

In here I'm trying to load the queried data from MySQL.

<div id="menu-container">
    <div id="menu">
        <span class="text"><a href="{{address}}">{{text}}</a></span>
        <span class="text"><a href="/">Home</a></span>
         <span class="text"><a href="/services">Services</a></span>
        <span class="text"><a href="/contact">Contact</a></span>
    </div>
</div>

I just started learning Node.js two days ago. I was able to figure out how to use the partials with Mustache, but I can't figure out MySQL. I already created the necessary tables in the node database.

MySQL

 menu
 -> ID (INT) -> 1
 -> Address (Text) -> www.example.com
 -> Text (Text) -> Test

How can I fix this problem?

It's quite hard to find good Node.js manuals.

Était-ce utile?

La solution

The query() is async, so you have to move the code after your query() call inside the query() callback like so:

app.get('/', function(req, res, next) {
  var sql = 'SELECT * FROM menu WHERE id = 1';
  connection.query(sql, function(err, results) {
    if (err) return next(err);
    for (var i = 0, len = results.length; i < len; ++i) {
      var sqlResult = results[i];
      console.log(sqlResult['address'], sqlResult['text']);
    }
    res.render('index', {
      address: results[0].address,
      text: results[0].text
    });
  });
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top