文件结构
安装
- Node.js
- express
npm install -g express
- express-generator
npm install -g express-generator
创建项目
- 使用
express express-backend
创建出一个项目,express-backend
为项目名称。
- 进入项目文件夹,执行
npm install
安装相关依赖。
- 启动项目
npm start
,在浏览器输入http://localhost:3000/
即可访问了,效果如下:
连接数据库MySQL
数据库结构如下:
- 安装MySQL依赖,
npm install --save mysql
- 在根目录下新建
config/index.js
文件配置数据库
allowClient: ["localhost:3000", "127.0.0.1:3000"],
mysql: {
host: 'localhost',
port: '3306',
user: 'root',
password: 'root',
database: 'test',
multipleStatements: true,
waitForConnections: true,
charset: "UTF8MB4_UNICODE_CI"
},
};
- 在根目录下新建
utils/db.js
文件,
const mysql = require('mysql');
const config = require('../config');
const pool = mysql.createPool(config.mysql);
pool.on('connection', (connection) => {
});
pool.on('release', (connection) => {
});
pool.on("error", (err) => {
console.error(err);
});
const getConnection = (res) => {
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) {
console.error(err);
if (res) {
res.send( {
code: "000001",
msg: "对不起,您还未获得授权",
});
}
reject(err)
} else {
resolve(connection)
}
});
});
};
const execQuery = (options, connection, release = true) => {
return new Promise((resolve, reject) => {
connection.query(options, function (error, result, field) {
if (release) {
connection.release();
}
if (error) {
reject(error)
} else {
resolve({
result,
field,
})
}
});
})
};
const query = (options, connection, release) => {
if (connection) {
return execQuery(options, connection, release)
} else {
return getConnection().then(connection => {
return execQuery(options, connection, release)
})
}
};
const execTransaction = (connection, task) => {
return new Promise((resolve, reject) => {
connection.beginTransaction(function(err) {
if (err) {
reject(err)
}
task.then(resp => {
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
reject(err)
});
} else {
resolve(resp)
}
});
}, err => {
connection.rollback(function() {
reject(err)
});
}).catch(err => {
connection.rollback(function() {
reject(err)
});
})
});
}).finally(() => {
connection.release();
})
};
module.exports.getConnection = getConnection;
module.exports.query = query;
module.exports.execTransaction = execTransaction;
- 根目录下新建
sql/index.js
文件
const user = require('./user.js');
module.exports = {
...user,
};
- 根目录下新建
sql/user.js
文件
module.exports = {
QueryAll: 'SELECT * FROM user',
};
- 修改
routes/users.js
文件
var express = require('express');
var router = express.Router();
const indexSQL = require('../sql');
const dbUtils = require('../utils/db');
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/list', (req, res, next) => {
dbUtils.query({
sql: indexSQL.QueryAll,
}).then(({ result }) => {
if (result) {
res.send({
code: '0',
data: result,
});
} else {
res.send({
code: '003001',
data: [],
});
}
});
});
module.exports = router;
- 调用接口,结果如下: