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. angular.js - 輸入郵箱地址之后, 如何使其自動在末尾添加分號?2. javascript - JS 里面的 delete object.key 到底刪除了什么?3. mysql - 電商如何存儲營業額數據4. javascript - 后臺管理系統左側折疊導航欄數據較多,怎么樣直接通過搜索去定位到具體某一個菜單項位置,并展開當前菜單5. 管理員信息修改時的密碼問題6. android - RxJava 中有根據條件執行不同函數的操作符嗎?7. javascript - html5的data屬性怎么指定一個function函數呢?8. java如何生成token?9. javascript - 如何使用nodejs 將.html 文件轉化成canvas10. html5 - 為什么使使用vue cli 腳手架,post-css 沒有自動對css3屬性自動添加瀏覽器前綴呢?
