首先在route文件夹内设置路由
var userController = require('../controllers/user.control.server');
module.exports = function(app){
app.route('/userList')
.get(userController.list)
.post(userController.create)
.put(userController.edit)
.delete(userController.delete);
app.route('/userList/:id')
.get(userController.detail);
app.route('/user/login')
.post(userController.login);
}
mysql数据库连接文件如下
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database : 'cms_demo'
});
connection.connect();
module.exports = connection;
错误处理及通用中间件文件express.js文件如下
var express = require('express')
var app = express();
const cors = require("cors");
var bodyParser = require('body-parser')
app.use(cors()); //就这一步就已经解决了跨域
app.use(bodyParser.json());
// 每次应用程序收到请求时,它将消息“ LOGGED”打印到终端。
// 中间件加载的顺序很重要:首先加载的中间件功能也将首先执行。
// 如果myLogger在到达根路径的路由之后加载,则请求永远不会到达请求,并且应用程序不会显示“ LOGGED”,因为根路径的路由处理程序会终止请求-响应周期。
// 中间件函数myLogger仅打印一条消息,然后通过调用该next()函数将请求传递到堆栈中的下一个中间件函数。
var myLogger = function (req, res, next) { //通用中间件功能,打印一段字符串
console.log('LOGGED')
next() //回调函数,表示进入下一步
}
app.use(myLogger)
module.exports = function(){
console.log('init express...');
require('../route/user.route.server')(app)
app.use(function(req, res, next){
res.status(404);
try{
return res.json('not found')
}catch(e){
console.log(e)
}
});
app.use(function(err, req, res, next){
if(!err){
return next()
};
res.status(500);
try{
return res.json(err.message || 'server error')
}catch(e){
console.log(e)
}
})
return app;
}
然后编写简单的控制器文件user.control.server.js
var express = require('express')
var app = express();
const uuidv1 = require('uuid/v1');
const cors = require("cors");
const crypto = require("crypto"); //node自带的密码加密
// const { get } = require("axios").default; //利用axois发送个网络请求
app.use(cors()); //就这一步就已经解决了跨域
var connection = require('../mysql');
module.exports = {
list:app.get('/userList', (req,res)=>{
var start = (req.query.pageNum-1)*req.query.pageSize
var end = req.query.pageNum*req.query.pageSize
new Promise(function(resolve, reject){
connection.query(`select count(id) from user where username like '%${req.query.name}%'`, function (error, results, fields) { //查列表
if (error) throw error;
var total = results[0][`count(id)`]
resolve(total)
});
}).then((data)=>{
connection.query(`SELECT * FROM user where username like '%${req.query.name}%' LIMIT ${start},${end}`, function (error, results, fields) { //查列表
if (error) throw error;
res.json({
code:'0',
data:results,
total:data,
msg:''
});
});
})
}),
detail:app.get('/userList/:id', (req,res)=>{
let id = req.params.id
connection.query('SELECT * FROM user where id = "' + id +'"', function (error, results, fields) { //查详情
if (error) throw error;
res.json({
code:'0',
data:results,
msg:''
});
});
}),
create:app.post('/userList', (req,res)=>{
connection.query('SELECT username FROM user where username = ? ',[req.body.username], function (error, results, fields) { //查列表
if (error) throw error;
if(results.length>0){
res.json({
code:'10010',
data:[],
msg:'用户名已存在'
});
return;
} else {
var addSql = 'INSERT INTO user(Id,username,userage,password) VALUES(?,?,?,?)';
var id = uuidv1();
if(!req.body.userage){
req.body.userage = null
}
let md5 = crypto.createHash("md5");
let newPas = md5.update(req.body.password).digest("hex");
var addSqlParams = [id, req.body.username, req.body.userage, newPas];
connection.query(addSql,addSqlParams,function (err, result) { //增
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
res.json({
code:'0',
data:'',
msg:'成功'
});
});
}
});
}),
edit:app.put('/userList', (req,res)=>{
var modSql = 'UPDATE user SET username = ?,userage = ? WHERE Id = ?';
var modSqlParams = [req.body.username, req.body.userage, req.body.id];
console.log(modSqlParams)
connection.query(modSql,modSqlParams,function (err, result) {
if(err){
console.log('[UPDATE ERROR] - ',err.message);
return;
}
console.log('--------------------------UPDATE----------------------------');
console.log('UPDATE affectedRows',result);
res.json({
code:'0',
data:'',
msg:'成功'
});
console.log('-----------------------------------------------------------------\n\n');
});
}),
delete:app.delete('/userList', (req,res)=>{
var delSql = 'DELETE FROM user where id= ?';
connection.query(delSql,[req.body[0]], function (err, result) {
if(err){
console.log('[DELETE ERROR] - ',err.message);
return;
}
console.log('--------------------------DELETE----------------------------');
console.log('DELETE affectedRows',result);
res.json({
code:'0',
data:'',
msg:'成功'
});
console.log('-----------------------------------------------------------------\n\n');
});
}),
login:app.post('/user/login', (req,res)=>{
let name = req.body.username;
let password = req.body.password;
let md5 = crypto.createHash("md5");
let newPas = md5.update(password).digest("hex");
connection.query('SELECT * FROM user where username = ? ',[name], function (error, results, fields) { //查列表
if (error) throw error;
console.log(results)
if(results.length === 0){
res.json({
code:'10020',
data:[],
msg:'用户不存在'
});
return;
}
else if(results[0].password !== newPas){
res.json({
code:'10030',
data:[],
msg:'密码错误'
});
return;
} else if(results[0].password === newPas){
res.json({
code:'0',
data:[],
msg:'登录成功'
});
return;
} else {
res.json({
code:'999',
data:[],
msg:'未知错误'
});
return;
}
});
}),
}
附上git小demo:https://github.com/wangjianan05/nodejsUseMysql.git