模块化
约 204 字小于 1 分钟
2025-07-25
路由抽离
当路由太多时,我们可以将路由抽离成模块,在其中加载一个 router 函数,定义一些路由,并将路由器模块挂载到主应用程序的某个路径上。
在 app
目录中创建一个名为 birds.js
的路由文件,内容如下:
const express = require("express");
const router = express.Router();
// middleware that is specific to this router
const timeLog = (req, res, next) => {
console.log("Time: ", Date.now());
next();
};
router.use(timeLog);
// define the home page route
router.get("/", (req, res) => {
res.send("Birds home page");
});
// define the about route
router.get("/about", (req, res) => {
res.send("About birds");
});
module.exports = router;
创建一个名为 app.js
的文件,并添加以下内容:
const express = require("express");
const app = express();
const birds = require("./birds");
app.use("/birds", birds);
app.listen(3000, () => {
console.log("Server is running on port 3000");
})
当需要响应 About birds 时,则访问路由为 http://localhost:3000/birds/about
。