首先,放上項目github地址:https://github.com/codethereforam/express mysql demo 一、前言 之前學的java,一直用的ssm框架寫後臺。前段時間接觸到node.js,於是花了兩天時間學了一下node.js並寫了一個CRUD簡單示例。由於前幾天一 ...
首先,放上項目github地址:https://github.com/codethereforam/express-mysql-demo
一、前言
之前學的java,一直用的ssm框架寫後臺。前段時間接觸到node.js,於是花了兩天時間學了一下node.js並寫了一個CRUD簡單示例。由於前幾天一直學用github pages搭建博客,一直沒時間寫README,今天有空補了上來。
下麵來內容自於項目的README。
二、項目介紹
基於node.js + express + mysql實現的restful風格的CRUD簡單示例
2.1 組織結構
├── app.js -- 應用配置
├── bin
│ └── www -- 項目運行腳本
├── conf
│ └── mysqlConf.js -- mysql配置文件
├── dao
│ ├── userDAO.js -- 封裝和資料庫的交互
│ └── userSqlMap.js -- SQL語句封裝
├── model
│ └── result.js -- 返回結果對象封裝
├── package.json -- 依賴模塊
├── project-datamodel
│ └── user.sql -- 資料庫腳本
├── public -- 前端靜態頁面
│ ├── add.html
│ ├── css
│ │ └── style.css
│ ├── detail.html
│ ├── index.html
│ └── modify.html
└── routes
└── users.js -- 用戶操作路由及業務邏輯
2.2 模塊依賴
www -> app.js -> users.js -> userDAO.js -> mysqlConf.js & userSqlMap.js
2.3 技術選型
後端技術
- node.js
- express
前端技術
- angular.js
三、環境搭建
- node.js: https://nodejs.org/en/download/package-manager/
- mysql: https://dev.mysql.com/doc/refman/5.7/en/installing.html
四、項目運行
- 下載代碼並部署
git clone https://github.com/codethereforam/express-mysql-demo.git
cd express-mysql-demo && npm install #安裝部署依賴的包
新建express-mysql-demo資料庫,導入project-datamodel文件夾下的user.sql
修改conf/mysqlConf.js中資料庫配置信息
啟動
# 切換到項目根路徑
npm start
- 打開首頁: http://localhost:8888
五、開發過程及代碼分析
關於restful,可參考阮一峰的兩篇文章:
我使用的IDE是IDEA,安裝"NodeJS"插件後依次點擊
File -> New Project -> Node.js and NPM -> Node.js Express App
IDEA預設使用express-generator生成項目結構。
新建資料庫"express-mysql-demo":
create database `express-mysql-demo`;
新建user表:
CREATE TABLE `express-mysql-demo`.`user` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45) NOT NULL,
`password` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
DEFAULT CHARACTER SET = utf8mb4;
表結構:
+----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| username | varchar(45) | NO | | NULL | |
| password | varchar(45) | NO | | NULL | |
+----------+------------------+------+-----+---------+----------------+
mysql配置文件conf/mysqlConf.js:
module.exports = {
mysql: {
host: 'localhost',
user: 'root',
password: '',
database:'express-mysql-demo',
// 最大連接數,預設為10
connectionLimit: 10
}
};
SQL語句封裝模塊dao/userSqlMap.js:
var userSqlMap = {
add: 'insert into user(username, password) values(?, ?)',
deleteById: 'delete from user where id = ?',
update: 'update user set username=?, password=? where id=?',
list: 'select * from user',
getById: 'select * from user where id = ?'
};
封裝返回結果對象model/result.js:
exports.createResult = function(success, data) {
var result = {};
result.success = success;
result.data = data;
return result;
};
我這裡使用了工廠方法創建結果對象,對象有兩個屬性,success代表用戶操作成功或失敗,data存放後臺要返回的數據。
下麵分析修改用戶部分信息的相關代碼,全部的增刪改查代碼請將項目clone下來查看。
封裝和資料庫的交互模塊dao/userDAO.js:
var pool = mysql.createPool(mysqlConf.mysql);
module.exports = {
getById: function (id, callback) {
pool.query(userSqlMap.getById, id, function (error, result) {
if (error) throw error;
console.log(result[0]);
callback(result[0]);
});
},update: function (user, callback) {
pool.query(userSqlMap.update, [user.username, user.password, user.id], function (error, result) {
if (error) throw error;
callback(result.affectedRows > 0);
});
}
};
這裡使用了連接池,重覆使用資料庫連接,而不必每執行一次CRUD操作就獲取、釋放一次資料庫連接,從而提高了對資料庫操作的性能。
用戶操作路由及實現業務邏輯routes/users.js:
/* patch users */
router.patch('/:id', function (req, res) {
console.log('patch users called');
userDAO.getById(req.params.id, function (user) {
var username = req.body.username;
if(username) {
user.username = username;
}
var password = req.body.password;
if(password) {
user.password = password;
}
console.log(user);
userDAO.update(user, function (success) {
var r = result.createResult(success, null);
res.json(r);
});
});
});
router根據不同的HTTP請求方法和訪問路徑執行相應的回調函數,回調函數中先記錄日誌,然後檢查用戶傳過來的數據,接著調用userDAO的相應CRUD方法,最後返回一個JSON對象給前端。這裡修改用戶部分信息對應HTTP方法是PATCH,而修改全部信息對應的是PUT。
應用配置app.js中配置用戶操作相關的路由:
app.use('/users', users);
前端public/index.html中與後臺交互的JS代碼:
(function (window) {
window.angular.module('list', [])
.controller('listCtrl', function ($scope, $http) {
$scope.doPatch = function (id) {
var data = JSON.stringify({
password: document.getElementById("pwd" + id).value
});
$http.patch("/users/" + id, data)
.then(function (response) {
console.debug(response.data.success);
}, function (err) {
alert(err);
});
};
});
})(window);
前端使用angualr.js,ajax非同步調用後端restful API,然後解析後臺返回的JSON對象在界面上展示。