简体   繁体   中英

In Nodejs Express App Route is not working

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.

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

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM