简体   繁体   中英

Need help in node.js Jade

I would like to seek help on displaying mySQL records in node.js Jade. I have followed the basic tutorial of node.js Jade and able to get it work by displaying default index.jade but when I start to implement mySQL connection link and function in my index.js, it display none and shows no data received on browser. Hope you guys could help me out with it as soon as possible, thanks in advance, guys.

This is my app.js:

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('port', process.env.PORT || 3000);

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
var server = app.listen(app.get('port'), function() {
  console.log('Listening on port %d', server.address().port);
});

This is my routes/index.js:

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

var conn = {
   host: 'localhost',
   user: 'user',
   password: 'password',
   database: 'rest_api',
   port: '3306'
};

/* GET home page. */
router.get('/', function(req, res) {
   exports.index = function(req, res) {
         var connection = mysql.createConnection(conn);
         var query ='SELECT sensorId, sensors, pinNo, sensorsType FROM sensorInfo';
         connection.query(query, function(err, rows, fields) {
                   if(err) throw err;
                res.render('index', { title: 'Sensor REST API', 'items': rows });    
         });
   };
});

module.exports = router;

This is my /views/index.jade:

extends layout

block content
    h1= title
    p Welcome to #{title}
    table
        tr
            th Sensor ID
            th Sensors
       th Pin Number
       th Sensors Type
        -each item in items
            tr
                td=item.sensorid
                td=item.sensors
      td=item.pinNo
      td=item.sensorsType

This is my sensorInfo structure:

CREATE TABLE IF NOT EXISTS `sensorInfo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sensorId` int(11) NOT NULL,
  `sensors` text COLLATE utf8_unicode_ci NOT NULL,
  `pinNo` int(11) NOT NULL,
  `sensorsType` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;

This is my records which I wanted to display it out from my sensorInfo:

--
-- Dumping data for table `sensorInfo`
--

INSERT INTO `sensorInfo` (`id`, `sensorId`, `sensors`, `pinNo`, `sensorsType`) VALUES
(1, 1, 'Red LED', 7, 'Switch ON/OFF'),
(2, 2, 'Blue LED', 11, 'Switch ON/OFF'),
(3, 3, 'Green LED', 13, 'Switch ON/OFF');

Remove the exports call from your router function - from

exports.index = function(req, res) {
    var connection = mysql.createConnection(conn);
    var query ='SELECT sensorId, sensors, pinNo, sensorsType FROM sensorInfo';
    connection.query(query, function(err, rows, fields) {
              if(err) throw err;
           res.render('index', { title: 'Sensor REST API', 'items': rows });    
    });
};

to

var connection = mysql.createConnection(conn);
var query ='SELECT sensorId, sensors, pinNo, sensorsType FROM sensorInfo';
connection.query(query, function(err, rows, fields) {
    if (err) throw err;
    res.render('index', { title: 'Sensor REST API', 'items': rows });    
});

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