I've created a NodeJS Express app. But my express route is invocking multiple routes function, one after another, but I only need one at a time.
My express app.js
app.use(routes)
Express router:
const router = express.Router();
router.post("/product", controller.productFunction)
router.post("/user", controller.userFunction)
router.get("/:id", idController.getId)
Whenever I create a post request for "/product"
route, first the productFunction
is invocked, but then the "/:id"
routes getId
function is also get invocked. Same thing happen for /user
route as well. Always /:id
route is getting invocked.
Is there any way to prevent this?
I even tried this way, but after the homepage loading then again it invockes getId
function.
app.get("/", (req, res, next) => {
res.sendFile(..........);
});
app.use(routes);
I am sure that this is not an issue with the router itself.
You can't skip from POST to GET handling. So invocations are caused by different requests.
router.get("/:id", idController.getId)
kind of wild card, and <server_url>/favicon.ico
will trigger it
If you check it via browser it tries to get favicon or smth else and invokes this handler.
Try to make POST
request via curl/Postman and idController.getId
should not be called.
It is risky to serve static and process requests on a same level.
You can add some prefix to all your request, like that app.use('/api', routes);
then static file will be available on /<file_name>
and all server logic will be under /api/<request>