Node.js + Node-MySQL + Express 4 + Moustache

时间:2014-05-11 21:26:01

标签: javascript mysql node.js express mustache

我正在尝试使用Node.js,而且我有点卡住了。我正在尝试将查询传递给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(部分)

在这里,我正在尝试从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>

两天前我刚开始学习Node.js。我能够弄清楚如何使用Mustache的部分,但我无法弄清楚MySQL。我已经在节点数据库中创建了必要的表。

的MySQL

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

如何解决此问题?

很难找到好的Node.js手册。

1 个答案:

答案 0 :(得分:1)

query()是异步的,所以你必须在查询()调用中的query()调用之后移动代码,如下所示:

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