【问题标题】:How to use NodeJS + ExpressJS to pass an array to Jade for display?如何使用 NodeJS + ExpressJS 将数组传递给 Jade 进行显示?
【发布时间】:2013-04-18 18:27:38
【问题描述】:

我来自一种非常“功能性”的编程风格(PHP、Lua、C),我正在尝试将我的想法转变为 NodeJS 使用的 MVC 模型。目前,这对我来说是一个非常陡峭的学习曲线。

我一直在拼命想将一个简单的 MySQL 数组打印到 Jade。

app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , mysql = require('mysql');

var app = express();


// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

//MySQL
var sqlInfo = {
  host: '12.34.56.78', 
  user: 'user',
  password: 'pass', 
  database: 'user'
}

var client = mysql.createConnection(sqlInfo);
client.connect();

client.query( "SELECT * FROM list ORDER BY status ASC LIMIT 25", function(err, row, fields){
  if (err) throw err;
  else {
    var applications = row;
    app.render("applications", applications, function(err, html){});
  }  
});

client.end();

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

index.jade

extends layout

block content
  div.container
    div.content   
      - if (typeof(applications) !== 'undefined')
        ul
          - each app in data
            li= app.status
      - else
        p Blank slate mate...

  div.footer

我认为我的问题源于 app.render/res.render 函数......这个函数的概念并不是真正的点击,我在让它工作时遇到了问题,就像我在许多其他函数中看到的那样MySQL + NodeJS 示例。

非常感谢任何提示或提示!

【问题讨论】:

    标签: javascript mysql node.js express pug


    【解决方案1】:

    问题是您试图在 HTTP 流之外呈现查询。这可能是您的意图(在这种情况下,我有兴趣了解您究竟想对呈现的结果做什么),但通常,您在返回结果之前等待 HTTP 请求您的查询。

    例如:

    app.get('/test', function(req, res) {
      // connect to MySQL server
      var client = mysql.createConnection(sqlInfo);
      client.connect();
    
      // Perform query and wait for results
      client.query( "SELECT * FROM list ORDER BY status ASC LIMIT 25", function(err, row, fields) {
        // Done with the connection
        client.end();
    
        // Handle error
        if (err) throw err;
        else {
          // We got a result: render it
          var applications = row;
          res.render("applications", { applications : applications });
        }
      });
    });
    

    几点建议:

    • 可以打开http://localhost:PORT/test查看结果
    • 看看connection pooling for MySQL,它维护一个与 MySQL 服务器的连接池,而不必在每次处理请求时都创建一个新连接;
    • 在您的示例代码中,您在client.query() 之后立即发送client.end(),但没有等待查询返回任何结果。所以我将client.end() 移到处理查询结果的代码内部,以确保只有在返回结果后才结束连接;
    • 在您的模板中,您引用了一个名为data 的变量,但我认为应该是applications;

    【讨论】:

      【解决方案2】:

      我可以在这里看到两个问题。

      首先,您将"applications" 作为第一个参数传递给app.render()。这应该是 "index" 以匹配您的视图名称。

      其次,我认为您缺少的关键点是您需要在传递给 app.render() 的函数中使用 html 做一些事情。

      app.render("applications", applications, function(err, html){
          //see what you have for html here
      });
      

      将函数传入渲染背后的想法是它像回调一样工作。您可以检查 err 以查看渲染视图是否存在问题。如果没有错误,html 应该具有基于 Jade 模板和您传入的任何数据 (applications) 呈现的 HTML。

      如果您仍有问题,我有几个建议。您可能应该调试您的数据以查看其外观。确保 MySQL 查询以您期望的格式返回数据。然后您可以查看您的模板是否有效。尝试传入一个简单的数据对象并首先使用一个简单的 Jade 模板,以确保您正确调用 app.render()。

      希望对你有帮助!

      【讨论】:

        【解决方案3】:

        您可以在渲染视图时将变量传递给jade:

        res.render('index', { applications: applications }, function(err, html){});
        

        然后你可以在你的 index.jade 中使用它:

        if (typeof(applications) !== 'undefined')
        

        【讨论】:

        • 不能使用 res.render 我不相信。 (除非我想把它放在 ExpressJS 应用程序的 app.get 或 router/index.js 中)像建议的那样格式化数组也不起作用。
        猜你喜欢
        • 2012-11-18
        • 1970-01-01
        • 2014-05-03
        • 1970-01-01
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多