Express路由器参数 - 使用URL链接

Ada*_*son 1 node.js express

我在Express中定义了一个完整的CRUD API,我想删除基础的重复并使用时髦的route功能,但我担心这是不可能的.

当前:

var router = express.Router();
var base = '/api/foo/bar/';
router.get(base, this.list);
router.get(base + ':id', this.read);
router.post(base, this.create);
router.put(base + :id', this.update);
router.del(base + :id', this.del);
Run Code Online (Sandbox Code Playgroud)

期望:

var router = express.Router();
router.route('/api/foo/bar')
  .get(this.list)
  .get(':id', this.read)
  .post(this.create)
  .put(':id', this.update)
  .del(':id', this.del)
Run Code Online (Sandbox Code Playgroud)

问题是动词函数(get,post,put,del)不接受字符串作为它们的第一个参数.

是否有类似的方法来实现这一目标?

msc*_*dex 7

重要提示:使用此技术会起作用,但我们知道,从Express 4.3.2开始,嵌套路由器上定义的所有子路由都无法访问req.params其外部定义的内容,也无法访问param中间件.它完全被隔离了.但是,这可能会在以后的4X版本中发生变化.有关更多(最新)信息,请参阅https://github.com/visionmedia/express/issues/2151.


怎么样呢:

// api.js
var router = express.Router();
router
  .route('/')
    .get(this.list)
    .post(this.create);
router
  .route('/:id')
    .get(this.read)
    .put(this.update)
    .del(this.del);
module.exports = router;

// app.js / main.js
app.use('/api/foo/bar', require('./api'));
Run Code Online (Sandbox Code Playgroud)

或者如果你想一次链接所有这些:

// api.js
var router = express.Router();
router
  .get('/', this.list)
  .get('/:id', this.read)
  .post('/', this.create)
  .put('/:id', this.update)
  .del('/:id', this.del);
module.exports = router;

// app.js / main.js
app.use('/api/foo/bar', require('./api'));
Run Code Online (Sandbox Code Playgroud)