使用express應用生成器生成express模板後,先寫package.json前端
{ "name": "mysql-test", "version": "0.0.1", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.13.2", "cookie-parser": "~1.3.5", "debug": "~2.2.0", "ejs": "~2.3.3", "express": "~4.13.1", "morgan": "~1.6.1", "serve-favicon": "~2.3.0", "mysql":"*" } }
npm install安裝依賴node
新創建兩個文件夾,models和configmysql
寫一個config配置文件,去鏈接mysql的:sql
module.exports = { mysql_dev: { host: 'localhost', user: 'user', password: 'your password', database: 'your db name', connectionLimit: 10, supportBigNumbers: true } };
再寫上一個database.js文件:express
var mysql = require('mysql'); var config = require('../config/config'); var pool = mysql.createPool(config.mysql_dev); exports.pool = pool;
在models裏創建一個User.js文件做爲model:npm
var db = require('./database'); 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裏引入,再調用:json
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請求。後端