1

I have an app.js file as -

const express = require('express');
const app = express();
const port = process.env.PORT || 8080;

const userRoute = require('./routes/user.route');
app.use('/user', userRoute);

app.listen(port, () => {
        console.log(chalk.blue(`Express app listening at http://localhost:${port}`));
});

My route file is -

const express = require('express');
const router = express.Router();

const userController = require('../controllers/user.controller');

router.post('/:id', userController.userDetails);
router.post('/toggleActive', userController.toggleStatus);

module.exports = router;

I am unable to reach '/toggleActive' path.

But if i define route file as -

router.post('/toggleActive', userController.toggleStatus);
router.post('/:id', userController.userDetails);

module.exports = router;

Then everything is working fine.

Abhishek
  • 77
  • 1
  • 7

2 Answers2

2

If you define routes like this

router.post('/:id', userController.userDetails);
router.post('/toggleActive', userController.toggleStatus);

then server will catch everything that is sent with POST to /user because :id is a variable. It might as well be a string "toggleActive". You can do something like this

router.post('/:id/toggleActive', userController.toggleStatus);
router.post('/:id', userController.userDetails);
szulbix
  • 146
  • 1
  • 9
1

Your url

/user/toogleActive
will be matched by the route with the path. Meaning the first route defined will be matched by the url which will extract toogleActive as a param. However to change this, route
/toogleActive
should be placed before as a to achieve the first matching policy used by express.
Divin Irakiza
  • 317
  • 1
  • 7