Router application of node.js back-end service

In the previous article, "Node Back-end Service Construction" talked about how to build node, and today I will record how to modularize the back-end service, just like front-end projects (like Vue), different pages, we use router to divide. Then, for backend projects built with node.js, we can also use router to distinguish different modules.
1. For example, our project mainly has three functions of homepage, product, and personal center; then we need to split the api of these three functions into three modules, so we are creating three new api applications in parallel with package.json The directories are app-home-api, app-product-api, and app-user-api.
2. Create two new js in app-home-api (divided into controller and service layers according to the back-end springMVC writing method): app-home-controller.js, app-home-service.js
3. In app-home-controller.js we only manage the interface, for example:

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. In app-home-service.js, we process business logic, generally query data or judge parameters, etc.

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. The same logic for the other two applications;
6. In index.js, we modify it as follows;

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. Start the service

npm run start

8. Call the api of app-home-controller.js and use postman to splice the local ip+/home/getHomeInfo.

Guess you like

Origin blog.csdn.net/weixin_43169949/article/details/113725353