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. python3.5 urllib.parse.unquote 乱码2. html5 - node静态资源服务器设置了Cache-Control,但浏览器从来不走3043. android - ionic应用打包部署了,但是连接不上服务器,就连写一个a标签链接到百度都不可以4. mysql - 这里的sql语句该怎么写5. Mysql 关于 FOUND_ROWS() 和 ROW_COUNT() 函数6. mysql - msyql 判断字段不为空 简单方法7. mysql - laravel 子查询的问题8. 老师百度网盘分享一下WampServer的包啊,我们下载几kb要下载一天的.9. mysql中的collate关键字是什么意思?10. mysql - 使用update语句同时更新两个表的问题?
