[Node.js]expressjs简单测试连接mysql

  下载好node.js和通过npm安装好express.js后,先写package.json

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/nodemon/bin/nodemon.js app.js"
  },
  "dependencies": {
    "express": "3.4.8",
    "jade": "*",
    "mysql":"*",
    "underscore":"*"
  },
  "devDependencies":{
    "nodemon":"*"
  }
}

nodemon是当js文件修改后,重新启动node.js进程,方便测试;

npm install安装依赖

其中一个start命令是用于启动服务器时,直接使用npm start来执行此命令;

新建立两个文件夹,models和config

写一个config配置文件,去连接mysql的:

module.exports = {
    mysql_dev: {
        host: 'localhost',
        user: 'dbu user',
        password: 'your password',
        database: 'your db name',
        connectionLimit: 10,
        supportBigNumbers: true
    }
};

再写上一个database.js文件:

var mysql = require('mysql');
var config = require('../config/config');

var pool = mysql.createPool(config.mysql_dev);

exports.pool = pool;

在models里建立一个User.js文件作为model:

var db = require('./database');
var _ = require('underscore');

var User = function() {};

User.prototype.find = function(id, callback) {
    var sql = "SELECT * FROM users WHERE id =?";
    // get a connection from the pool
    db.pool.getConnection(function(err, connection) {
        if (err) {
            callback(true);
            return;
        }
        // make the query
        connection.query(sql, [id], function(err, results) {
            if (err) {
                callback(true);
                return;
            }
            callback(false, results);
        });
    });
};

module.exports = User;

最后在app.js里引入,再调用:

var User = require('./models/User');

//.......

app.get('/users/:userid',function(req,res){
    var userid = req.params.userid;
    var user = new User();
    user.find(userid,function(err,result){
        if(err){
            res.send('not found');
        }
        res.send(result.length === 1 ? result[0]:result);
    });

});

这样就简单地完成一个后端的node.js分级结构,前端提供rest请求。

posted @ 2014-03-06 11:29  qgymje  阅读(1746)  评论(1编辑  收藏  举报