【发布时间】:2016-01-15 23:40:36
【问题描述】:
我对 node.js 很陌生,所以请多多包涵。
我想知道如何获取一个 mysql 实例并在我的控制器中使用它。我有 4 个如下所示的文件:
在 controller.js 文件中查看我的评论
server.js:
var express = require('./config/express');
var app = express();
module.exports = app;
app.listen(3000);
console.log('server running');
express.js:
var express = require('express'),
bodyParser = require('body-parser'),
mysql = require('mysql');
module.exports = function() {
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.set('views','./app/views');
app.set('view engine','ejs');
//NOT SURE WHAT TO DO HERE OR WHERE TO PUT THE CONNECTION DETAILS
var dbConnection = mysql.createConnection({
host : 'localhost',
user : 'someuser',
database : 'somedb',
password : 'somepass'
});
//connection.connect();
//
//connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
// if (err) throw err;
// console.log('The solution is: ', rows[0].solution);
//});
//
//connection.end();
require('../app/routes/index.server.routes.js')(app);
app.use(express.static('./public'));
return app;
};
routes.js:
module.exports = function(app) {
var index = require('../controllers/index.server.controller');
app.get('/', index.render);
app.post('/', index.stuff);
};
controller.js:
exports.render = function(req, res) {
//DO DB STUFF HERE
res.render('index', {
title: 'this is the title'
});
};
exports.stuff = function(req, res) {
res.render('index', {
title: 'this is the title post'
});
};
【问题讨论】:
-
这里的目标是使用 node.js 并设置 DBMS 吗?还是一定要用mysql?
-
所以您要附加到一些已经存在的数据源?
-
这可能有帮助,也可能没有帮助。 sitepoint.com/using-node-mysql-javascript-client
标签: javascript mysql express