mysql - node express 數據操作相關的邏輯怎樣封裝更合理?
問題描述
先上目錄結構
路由層代碼 router/
index.js
'use strict';module.exports = function (app) { app.get(’/’, function (req, res, next) {res.send(’Hello node-express World!’);next(); }); // 具體的業務請求路由配置 app.use(’/user’, require(’./user’)); // 404 page ejs渲染報錯,暫時不管 app.use(function (req, res) {if (!res.headersSent) { res.status(404); // res.status(404).render(’../view/404’);} });};
user.js
'use strict';var express = require(’express’);var router = express.Router();//mysqlvar user_pool = require('../mysql/user');// 該路由使用的中間件 timeLogrouter.use(function timeLog(req, res, next) { console.log(’Time: ’, Date.now()); next();});// 定義網站主頁的路由router.get(’/’, function (req, res) { // console.log(req); res.send(req.query || {});});// 查詢用戶信息router.post(’/infos’, function (req, res) { console.log(req.body); user_pool.query('select * from user where name=1104', function (data) {console.log('===============user query callback==========');console.log(data);res.send(data); });});//moremodule.exports = router;
數據層代碼 mysql/ mysql_pool.js
/** * Created by xiaogang on 2017/4/5. */'use strict';var config = require(’config-lite’);var mysql = require(’mysql’);var pool = mysql.createPool(config.mysql_pool);module.exports = pool;
user.js
/** * Created by xiaogang on 2017/4/5. */'use strict';var pool = require('./mysql_pool');exports.query = function (sql, callback) { pool.query(sql, function (error, results, fields) {if (error) throw error;callback(JSON.parse(JSON.stringify(results))); });}exports.update = function (sql, callback) { pool.query(sql, function (error, results, fields) {if (error) throw error;callback(JSON.parse(JSON.stringify(results))); });}
前端調用:zepto(jquery) 的ajax
問題:不知道各位經常寫后臺的認為這樣封裝可行不?希望多多吐槽。
前端開發轉node,目前只能封裝到這一步,后面要上項目的,還望多多指教。
問題解答
回答1:百度搜索sequelize,可以使用這個orm來操作數據庫,雖然性能方面會有些一影響,但是使用方便
相關文章:
1. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題2. javascript - QWebEngineView 如何爬 angular 的動態數據?3. javascript - 使用angular 的ui-sref 中出現了中文參數,點擊跳轉后瀏覽器的地址欄里出現轉義后的%AE....%a%44. java - ConcurrentHashMap中的get()方法為什么可以不加鎖?5. java - 郵箱如何發送html內容6. html5 - 這個代碼顯示功能如何實現?7. javascript - 用JS 七牛上傳圖片出現文件已存在的錯誤(file exists)8. 工作近5年,3年Java Web ,近2年前端,未來何去何從?9. css3 - 圖片等比例縮放10. java - 字節流轉成字符串之后,在通過字符串轉成字節流后的文件為什么會不一樣?
