How can I successfully configure my routes to access multiple methods on my controller accordingly to the endpoint and parameters passed to the URL?
When accessing /companies/:companyId/createCheques I would like to call the method createCheques in cheques controller but it is still calling createCheque.
I tried adding the line below to routes/cheques.js but it did not work.
router.route('/:companyId/createCheques').post(createCheques)
// routes/companies.js const express = require('express') const { getCompanies, getCompany, deleteCompany, createCompany, updateCompany, } = require('../controllers/companies') // Include other resource routers const userRouter = require('./users') const chequeRouter = require('./cheques') const redeemRouter = require('./redeems') const router = express.Router({ mergeParams: true }) // Re-route into another resources routers router.use('/:companyId/users', userRouter) router.use('/:companyId/cheques', chequeRouter) router.use('/:companyId/createCheques', chequeRouter) router.use('/:companyId/redeems', redeemRouter) router.route('/').get(getCompanies).post(createCompany) router.route('/:id').get(getCompany).put(updateCompany).delete(deleteCompany) module.exports = router;
// routes/cheques.js const express = require('express') const { getCheques, getCheque, deleteCheque, createCheque, createCheques, updateCheque } = require('../controllers/cheques') // when more than 1 url param is possible to the same route, mergeParams must to be set to true const router = express.Router({ mergeParams: true }) // Advanced results const Cheque = require('../models/Cheque') const advancedResults = require('../middleware/advancedResults') router.route('/').get(advancedResults(Cheque, 'cheques'), getCheques).post(createCheque).post(createCheques) router.route('/:id').get(getCheque).put(updateCheque).delete(deleteCheque) module.exports = router;
The problem you have is that you are defining two POST controllers for the exact same route.
If you want to call both controllers createCheque
and createCheques
, when a POST is done to :companyId/createCheques/
, you only need to add next()
on the last line of createCheque
, just like a middleware. See https://expressjs.com/es/4x/api.html#router
If you only want to call one controller, then you need to create a separate route for the other controller on your routes/cheques.js file.
router
.route('/cheques') //here the complete path would be companyId/createCheques/cheques
.post(createCheques)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.