基于nodejs搭建express服务框架
1.框架结构
- 框架实现
2-1 node_modules
`npm install express --save
2-2 index.js
const express = require("express");
const app = express();
const router = require("./router.js")
/**
- 参数1:全局路径
- 参数2:router
- **/
app.use("/api",router)
app.listen(3000,() =>{
console.log("服务器运行在3000端口上");
})
2-3 package.json
{
"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.18.2",
"mysql": "^2.18.1"
}
}
自动生成
2-4 router.js
const express = require("express");
const router = express.Router();
// 添加接口
router.get("/list",(req,res) =>{
res.send({
status:200,
message:"测试服务器"
})
})
module.exports = router;
2-5 SQLConnect.js
// 1.创建MySQL实例
const mysql = require("mysql");
// 2.创建MySQL对象
const MySQLObj = {
host:"localhost",
user:"root",
password:"",
database:"vue3_itbaizhan"
}
// 3.创建连接池
const pool = mysql.createPool(MySQLObj);
// 4.编写操作DB的相关逻辑
function SQLConnect(sql,arr,callback){
pool.getConnection((err,connection) =>{
if (err){
console.log(err);
return
}
connection.query(sql,arr,(err,result) =>{
// 释放连接
connection.release();
if (err){
console.log(err);
return
}
callback(result)
})
})
}
module.exports = SQLConnect