nodejs+express+mysql實現restful風格的增刪改查示例

首先,放上項目github地址:https://github.com/codethereforam/express-mysql-democss

1、前言

以前學的java,一直用的ssm框架寫後臺。前段時間接觸到node.js,因而花了兩天時間學了一下node.js並寫了一個CRUD簡單示例。因爲前幾天一直學用github pages搭建博客,一直沒時間寫README,今天有空補了上來。html

下面來內容自於項目的README前端

2、項目介紹

基於node.js + express + mysql實現的restful風格的CRUD簡單示例java

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

  • node.js
  • express

前端技術mysql

  • angular.js

3、環境搭建

4、項目運行

  1. 下載代碼並部署
git clone https://github.com/codethereforam/express-mysql-demo.git
cd express-mysql-demo && npm install   #安裝部署依賴的包
  1. 新建express-mysql-demo數據庫,導入project-datamodel文件夾下的user.sqlgit

  2. 修改conf/mysqlConf.js中數據庫配置信息github

  3. 啓動ajax

# 切換到項目根路徑
npm start
  1. 打開首頁: http://localhost:8888

5、開發過程及代碼分析

關於restful,可參考阮一峯的兩篇文章:sql

我使用的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對象在界面上展現。

相關文章
相關標籤/搜索