Home > Software design >  MERN pagination and filtering in same controller
MERN pagination and filtering in same controller

Time:04-19

How to do pagination and filtering at the backend in the same controller?

Filter service:-

const filterPosts = async (filterData, token) => {
    const config = {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      data: {
        filterData,
      },
    };
  
    const response = await axios.get(API_URL, config);
  
    return response.data;
  }

Route:-

router.route("/").get(protect, getPosts);

Controller:-

I cant seem to send the filterData from service to this controller, how to achieve it?

const getPosts = asyncHandler(async (req, res) => {

     console.log("filter data:- ", req.body); // This Part is undefined.

  
    //pagination
    const PAGE_SIZE = 6;
    const PAGE = parseInt(req.query.page || "0");
    const total = await Post.countDocuments({ user: req.user.id });
  
      
    const AllPosts = await Post.find({ user: req.user.id })
      .limit(PAGE_SIZE)
      .skip(PAGE_SIZE * PAGE)
      .sort({ createdAt: -1 });
  
    const totalPages = Math.ceil(total / PAGE_SIZE);
  
    res.status(200).json({ totalPages, Allposts });
  });

console.log("filter data:- ", req.body); // This Part is undefined.

CodePudding user response:

You can send this data using config.params in Get request or use Post request if you want to use config.data.

Sometimes XHR / Fetch do not allow payload in Get request. As per this axios doc, sending data as request body is only applicable for request methods PUT, POST, DELETE , and PATCH.

You can also refer to this issue for reference : Link

const filterPosts = async (filterData, token) => {
  const config = {
    headers: {
      Authorization: `Bearer ${token}`,
    },
    params: {
      filterData,
    },
  };

  const response = await axios.get(API_URL, config);

  return response.data;
}

  • Related