1. 项目结构
demo_project
| -- package.json
| -- app.js // 入口
| -- router // 接口请求URL到业务处理函数的映射关系
| -- index.js
| -- user.js
| -- ...
| -- controller // 业务处理
| -- index.js
| -- user.js
| -- ...
| -- db // 数据库配置相关
| -- index.js
| -- view // 页面静态资源
| -- index.html
| -- ...
2. MVC结构
3. 项目实现
3.1 项目版本信息(package.js)
npm int -y
3.2 项目入口(app.js)
// 1. 引入模块
const express = require("express");
// 2. 创建服务
const app = express()
// 3.业务处理
// 3.1 中间件注册(如有需要)
// 3.2 静态资源托管 (如有需要)
// 3.3 路由模块加载
const fs = require('fs')
const path = require('path')
fs.readdir(path.join(__dirname, './router'), (err, filenames) => {
if (err) return console.log('读取 router 目录中的路由失败!')
filenames.forEach(filename => {
const router = require(path.join(__dirname, './router', filename))
app.use(router)
})
})
// 4. 监听端口
app.listen("8080",()=>{
console.log("The server is running at http://127.0.0.1:8080")
})
3.3 路由模块(router/index.js)
// 1. 创建路由
const express = require("express");
const router = express.Router();
// 2. URL映射业务处理
const ctrl = require("../controller/index.js");
router.get("/", ctrl.showIndexPage);
// 3. 导出路由
module.exports = router
其他路由除了 URL映射业务处理不同,其余都相同
3.4 业务处理(controller/index.js)
// 1. 业务处理
const showIndexPage(req,res){
// do something
// 在业务处理中可能需要数据库处理
const connect = require("../db/index.js");
connect.query(sql, (err, res) => {
if(err) {
// do something
return
}
// do something
} )
}
...
// 2. 导出模块
module.exports = {
showIndexPage,
...
}
3.5 数据库连接(db/index.js)
// 1. 引入模块
const mysql = require("mysql");
// 2. 连接数据库
const connect = mysql.createConnection({
host: '',
database: '',
user: '',
password: '',
...
})
// 2. 导出数据库连接
module.exports = connection;