在上一篇文章《node后端服务搭建》讲到了node怎么搭建,今天记录下怎么把后台服务模块化,就像前端项目(像Vue),不同的页面,我们用router来划分。那么用node.js搭建的后端项目,我们也是可以用router来区分不同的模块。
1.比方说,我们这个项目主要有首页,产品,个人中心的三个功能;那么我们需要将这三个功能的api拆成3个模块,所以我们在与package.json并列新建三个api应用目录,分别为app-home-api、app-product-api、app-user-api.
2.在app-home-api里面新建2个js(按照后端springMVC的写法分为controller,service层):app-home-controller.js,app-home-service.js
3.在app-home-controller.js我们只管接口,例如:
const express = require('express');
const HomeService = require('./app-home-service')
const home = express.Router();
home.get('/getHomeInfo', (req, res) => {
const result = new HomeService().getInfo();
console.log(result)
res.json(result)
})
module.exports = home;
4.在app-home-service.js,我们处理业务逻辑,一般都是查询数据或者对参数作判断等等
const mysql = require('mysql');
function Result({ code = '1', msg = '请求成功', data = {} }) {
this.code = code;
this.msg = msg;
this.data = data;
}
const mysqlOption = {
host: 'xxx',
user: 'root',
password: '123456',
database: 'test'
}
let con = mysql.createConnection(mysqlOption)
class HomeService {
getInfo(res, req) {
let data;
try {
con.query(sql, (require, response) => {
//返回给前端的数据
data = new Result({ data: response })
})
} catch {
data = new Result({ data: response })
}
return data
}
}
module.exports = HomeService;
5.其他2个应用一样的逻辑;
6.在index.js里面,我们修改为如下;
const express = require('express');
const app = express();
app.use('/home', require('./app-home-api/app-home-controller'))
const port = process.env.port || '3000';
app.set('port', port)
app.listen(80, () => {
console.log("服务启动了")
})
//请求url找不到,设置请求状态为404
app.use((req, res) => {
res.sendStatus(404)
})
7.启动服务
npm run start
8.调用app-home-controller.js的api,用postman拼接本地ip+/home/getHomeInfo即可。