在 express 中假如我要做一批接口,都跟list有关系。
const express = require('express');
const app = express();
const port = 3000;
app.get('/list', function (req, res, next) {
res.json('get /list')
})
app.get('/list/:id', function (req, res, next) {
res.json('get /list/:id')
})
app.post('/list/:id', function (req, res, next) {
res.json('post /list/:id')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
如上,关于list有3个接口,但在实际开发中,关于list的接口可能几十上百个,如果统一写在这里肯定是不太现实的。它的请求都和list有关,有没有办法把list分离出来,在list这一组接口内部,只需写list后面的部分就行了,而list作为它们的公共前缀。这就需要用到router来处理了。
根目录下新建一个router目录,目录下新建list.router.js文件。在express中已经内置了通过router去处理请求的方式,可以通过 expres.Router拿到。
// router/list.router.js
const express = require("express");
const router = express.Router();
router.get("/", function (req, res, next) {
res.json("get /list");
});
router.get("/:id", function (req, res, next) {
res.json("get /list/:id");
});
router.post("/:id", function (req, res, next) {
res.json("post /list/:id");
});
module.exports = router;
再修改 index.js 文件如下。
const express = require("express");
const listRouter = require("./router/list.router");
const app = express();
const port = 3000;
app.use("/list", listRouter);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
所以如果有多个相关路由的话,在router文件夹下写就好了,然后暴露出去,在 index.js 里导入注册。
使用router去处理请求可以更好地管理和组织代码,进行模块化,中间件隔离。是更灵活的路由定义方式,使代码清晰,易于维护。
既然app.use和router.use都可以对请求进行处理,那具体该怎么选呢?
之所以我们可以在app对象里利用它的方法发起请求,那是因为在源码里面,express去结合各种router的方法进行处理,挂载在app上,最终还是调用了router上的方法。
/**
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
if (method === 'get' && arguments.length === 1) {
// app.get(setting)
return this.set(path);
}
this.lazyrouter();
var route = this._router.route(path);
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});