0

I got data from a local file. In response, I recieved the array with objects where I found the object I needed by ID. I understood that the object I need is in the data[user] by using the console.log.

router.param("id", (req, res, next, id) => {
  const fetchData = async () => {
    return await fs
      .readFile("backend/data/loggedUsers.json", "utf-8")
      .then((res) => {
        const data = JSON.parse(res);
        const user = data.findIndex((el) => el.id == id);
        req.user = data[user];
      });
  };
  fetchData();
  next();
});

But now I have to use this data in the get method, it doesn’t work out there.

router.get("/logged/:id", (req, res) => {
    res.json(req.user);
});

This code worked just with setTimeout, but I think that is not a good idea.

router.get("/logged/:id", (req, res) => {
  setTimeout(() => {
    res.json(req.user);
  }, 100);
});

0 Answers0