Home > Blockchain >  Express router going inside the same route
Express router going inside the same route

Time:01-27

I have setup 3 different routes which have their own subroutes

  router.use('/items', handleItems(app, router));
  router.use('/price', handlePrice(app, router));
  router.use('/documents', handleDocuments(app, router));

But when i call http://localhost:3000/api/documents/, it is throwing error as if it is calling functions inside /items routes. How can this happen?

After some more debugging i noticed that call is going inside handleItems handler to the /:id route

function handleItems(app, router) {
  router.post('/create-one', itemController.createItem);
  router.get('/:id', itemController.getItem);
  return router;
}

CodePudding user response:

This is because you're immediately invoking handleItems() and the other two. Remove the () and parameters so it becomes:

  router.use('/items', handleItems);
  router.use('/price', handlePrice);
  router.use('/documents', handleDocuments);

CodePudding user response:

Please refer to express.Router documentation.

In your example you have:

function handleItems(app, router) {
  router.post('/create-one', itemController.createItem);
  router.get('/:id', itemController.getItem);
  return router;
}

The first parameter is not used, and the second parameter is your router object, so basically, you are registering your routes in the same object and you will end up with something like

/items
/create-one
/:id
/price

What you are looking for is something like:

const { Router } = require("express");
const express = require("express");
const app = express();

app.use("/items", handleItems(Router()));
app.use("/documents", handleDocuments(Router()));

function handleItems(r) {
  r.get("/tada", (req, res) => res.json({ msg: `Tada` }));
  r.get("/:name", (req, res) => res.json({ msg: `Hello ${req.params.name}` }));
  return r;
}

function handleDocuments(r) {
  r.get("/", (req, res) => res.json({ msg: "Bonjour" }));
  return r;
}

app.listen(3000, () => console.log("           
  • Related