connect.js
const mysql = require(\'mysql\') const express = require(\'express\') const app = express() const router = express.Router(); // 解析参数 const bodyParser = require(\'body-parser\') let login = true; // json请求 app.use(bodyParser.json()) // 表单请求 app.use(bodyParser.urlencoded({extended: false})) const option = { host: \'localhost\', user: \'root\', password: \'root\', port: \'3306\', database: \'nodecms\', connectTimeout: 5000, //连接超时 multipleStatements: false //是否允许一个query中包含多条sql语句 } let pool; repool() function Result ({ code = 1, msg = \'\', data = {} }) { this.code = code; this.msg = msg; this.data = data; } // 断线重连机制 function repool() { // 创建连接池 pool = mysql.createPool({ ...option, waitForConnections: true, //当无连接池可用时,等待(true)还是抛错(false) connectionLimit: 100, //连接数限制 queueLimit: 0 //最大连接等待数(0为不限制) }) pool.on(\'error\', err => { err.code === \'PROTOCOL_CONNECTION_LOST\' && setTimeout(repool, 2000) }) app.all(\'*\', (_,__, next) => { pool.getConnection( err => { err && setTimeout(repool, 2000) || next() }) }) } module.exports = { app, pool, Result, router }router/login.js
const { pool, router, Result } = require(\'../connect\') router.get(\'/\', (req, res) => { pool.getConnection((err, conn) => { conn.query("SELECT * FROM students", (e, r) => { if(e) throw error res.json(new Result({ data: r })) }) pool.releaseConnection(conn) // 释放连接池,等待别的连接使用 }) }) module.exports = router;入口文件 index.js
const { app, pool, Result } =require(\'./connect\') const login = require(\'./router/login\') app.all(\'*\', (req, res, next) => { //这里处理全局拦截,一定要写在最上面 next() }) app.all(\'/\', (req, res) => { pool.getConnection((err, conn) => { res.json({ type: \'test\'}) pool.releaseConnection(conn) // 释放连接池,等待别的连接使用 }) }) app.use(\'/login\', login) app.listen(8088, () => { console.log(\'服务启动\') })package.json
{ "name": "api", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "hotnode index.js" }, "author": "yxf", "license": "ISC", "dependencies": { "body-parser": "^1.19.0", "cors": "^2.8.5", "express": "^4.17.1", "mysql": "^2.17.1" } }欢迎大家指出问题。共勉!、
下一篇具体实现登录、注册、修改密码、删除用户功能