문제

I have a full CRUD API defined in Express, and I'd like to remove the duplication of base and use the snazzy route function, but I fear it's not possible.

Current:

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);

Desired:

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)

The problem is that the verb functions (get, post, put, del) do not accept a string as their first parameter.

Is there a similar way to achieve this?

도움이 되었습니까?

해결책

Important: Using this technique will work, but we aware that as of Express 4.3.2, all subroutes defined on the nested router will not have access to req.params defined outside of it, nor param middleware. It's completely quarantined. This, however, is subject to change in a later 4X version. See https://github.com/visionmedia/express/issues/2151 for more (up to date) info.


How about this instead:

// 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'));

or if you want to chain all of them at once:

// 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'));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top