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. html5 - html img 标签 为什么会出现 image for resizing2. 多维数组遍历,求大佬解答???3. html - IOS二维码识别问题4. python3.x - python连oanda的模拟交易api获取json问题第五问5. javascript - 关于vue-cli每次都要build才能放到线上问题。6. 使用未定义的常量user_id-假定为“user_id”7. javascript - 怎么获取一个页面中的所数据,然后弄成一个json格式的字符串传给后台8. javascript - webpack异步加载js问题9. javascript - swiper2索引的问题10. python方法调用

网公网安备