1. 前置环境部署
1.1 安装node,请自行百度
1.2 创建一个文件夹放置node项目
1.3 在新建的node文件夹中执行npm init, 文件会生成一个package.json的文件
1.4 安装express框架, 及相关依赖
npm install express
npm install body-parser
npm install cors --save
1.5 创建相关文件目录
db文件夹:放置数据库操作语句(.js文件)
router文件夹:放置接口文件(.js文件)
connect.js文件:链接数据库前端等相关操作
index.js文件:主文件,引用各个文件,拦截请求,后端路由
2. connect.js
const mysql = require('mysql')
const express = require('express')
const app = express()
const router = express.Router();
const cors = require('cors');
const session = require("express-session");
const cookieParser=require("cookie-parser")
app.use(cors());
const bodyParser = require('body-parser')
app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.use(cookieParser());
app.use(
session({
secret:'keyboard cat',
resave:true,
saveUninitialized:true,
cookie:{
maxAge:1000*60*30,
secure:false
}
}))
const option = {
host: 'localhost',
user: '*****',
password: '*****',
port: '3306',
database: '*****',
connectTimeout: 5000,
multipleStatements: false
}
var allowCors = function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type,request-origin");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-control-max-age", 1000);
next();
};
app.use(allowCors);
let pool;
repool()
function Res ({ code = 200, msg = '', data = {} }) {
this.code = code;
this.msg = msg;
this.data = data;
}
function resJson (_res, result) {
if(result){
return _res.json(new Res(result))
}else{
return
}
}
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, router, resJson }
3. db文件夹(sql操作语句)
const SQL = {
queryAll: 'select * from biaoming order by si asc',
updateArt: 'update biaoming set si=? where si=?',
deleteArt: 'delete from biaoming where si=?',
addArt: 'insert into biaoming values (?,?,?,?,?,?)',
queryByIndex: 'select * from biaoming where si=?',
queryByLike: 'select * from biaoming where title like ?'
}
module.exports = SQL
4. router文件夹(接口文件)
const { pool, router, resJson } = require('../connect')
const userSQL = require('../db/userSQL')
const stringRandom = require('string-random');
router.get('/login', (req, res) => {
let user = {
username: req.query.name,
password: req.query.password
}
let _res = res;
if (!user.username) {
return resJson(_res, {
code: -1,
msg: '用户名不能为空'
})
}
if (!user.password) {
return resJson(_res, {
code: -1,
msg: '密码不能为空'
})
}
let _data;
const sessran = stringRandom(16, { numbers: true })
var usersess = req.session;
pool.getConnection((err, conn) => {
conn.query(userSQL.queryByNamePassword, [user.username, user.password], (e, result) => {
if (e) _data = {
code: -1,
msg: e
}
if (result && result.length) {
_data = {
msg: '登录成功',
data: {
userInfo: {
session: sessran
}
}
}
req.session.userinfo = sessran;
} else {
_data = {
code: -1,
msg: '用户名不存在或登录密码错误'
}
}
setTimeout(() => {
resJson(_res, _data)
}, 500);
})
pool.releaseConnection(conn)
})
})
module.exports = router;
5. index.js 入口文件
const { app, pool } =require('./connect')
const user = require('./router/user')
const page = require('./router/page')
app.all('*', (req, res, next) => {
next()
})
app.get('/', (req,res) => {
res.sendFile(__dirname+'/'+'index.html')
})
app.all('/', (req, res) => {
pool.getConnection((err, conn) => {
res.json({ type: 'test'})
pool.releaseConnection(conn)
})
})
app.use('/user', user)
app.use('/page', page)
app.listen(8088, () => {
console.log('服务启动','localhost:8088')
})
6. 启动服务
node index.js