npm init
npm install body-parser express mysql cors -S
引入路由,把页面拆分开:
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;
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
const option = {
host: 'localhost',
user: 'root',
password: 'root',
port: '3306',
database: 'yyds',
connectTimeout: 5000,
multipleStatements: false
}
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,
connectionLimit: 100,
queueLimit: 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 t_user", (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('服务启动')
})
|