Express extracts the routing module to create an http service

If the service is only created in a file, the maintenance is not high. At the same time, when the route is increased, the structure will be unclear. Therefore, the route module can be extracted separately and the maintenance operation can be carried out separately. But at this time there will be a problem, how to establish a connection between the service entry module app.js and the routing module router.js?
At the beginning, I usually think of exporting through the built-in object module.exports of the module, and importing it through app.js:

	// router.js
	module.exports = function(app) {
    
    
	app.get('/',(req,res) => {
    
    
		res.send('main');
	})
}
// app.js
 let express = require('express');
// 导入
let router = require('./router');
let app = express();
router(app);

Although the above method is also possible, the express framework has a corresponding solution for this aspect. It provides the Router() method to implement routing module extraction. The following is the specific construction process:

  1. Create a separate router.js file as a routing module, dedicated to processing different routes

  2. There is a method Router in express to create a routing container

    // router.js
    let express = require('express');
    // 创建路由容器
    let router = express.Router();
    
  3. Construct request through router

    // router.js
    router.get('/',(req,res) => {
          
          
        ress.send('hhh');
    })
    
  4. Export the router container in the router.js module

    module.exports = router;
    
  5. Import the router container in the service entry module

    // app.js
    let router = require('./router');
    
  6. Mount the router container in the service

    // app.js
    app.use(router);
    
  7. Complete example

    // router.js
    /**
     * 路由模块
     * 专门用于处理路由
     * 根据不同的请求+路径设置具体的处理方式
     */
    let express = require('express');
    // 创建一个路由容器
    let router = express.Router();
    // 通过路由容器存放请求
    router.get('/',(req,res) => {
          
          
        res.send('/路径');
    })
    
    router.get('/abc',(req,res) => {
          
          
        res.send('/abd路径');
    })
    
    // 导出路由容器
    module.exports = router;
    
    
    
    // --------------------------------------------
    // app.js
    /**
     * 入口模块
     * 启动服务
     * 做一些服务相关配置(提供静态资源服务,挂载路由)
     * 开启服务监听
     */
    let express = require('express');
    // 加载路由模块
    let router = require('./router');
    
    // 构建服务实例 相当于 http.createServer();
    let app = express();
    
    // 挂载路由
    app.use(router);
    
    // 绑定端口 相当于http.listen()
    app.listen(3000,()=> {
          
          
        console.log('server is running...');
    })
    

    After that, the way the client accesses the URL is the same as before.

Guess you like

Origin blog.csdn.net/chen__cheng/article/details/114788706