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. javascript - 自执行函数是当加载到这个js就执行函数了吗2. python 字符串匹配问题3. docker不显示端口映射呢?4. docker start -a dockername 老是卡住,什么情况?5. javascript - 这里的这个函数是干嘛用的?6. javascript - CSS图片轮播显示问题7. javascript - vue-router怎么不能实现跳转呢8. docker images显示的镜像过多,狗眼被亮瞎了,怎么办?9. android - viewpager问题PagerTabStrip样式10. dockerfile - 我用docker build的时候出现下边问题 麻烦帮我看一下
