Home > OS >  how do I get req.query nextjs api?
how do I get req.query nextjs api?

Time:10-26

I have this API, and I am trying to get the query I pass in the URL (such as products?page=1&limit=10) but I keep getting an empty object

const handler = nc().use(Cors());
handler.get(async (req, res) => {
    await db.connect();
    console.log(req.query)
    const products = await Product.paginate({}, { page: 1, limit: 30 });
    res.send(products);
});

export default handler;

CodePudding user response:

console.log(req.query.page, req.query.limit)

You can pass any props to your api

const desiredId = 'xyz'
'https://yourAPI/getSomething?any_name_you_want='  desiredId
//in your api
console.log(req.query.any_name_you_want)

CodePudding user response:

Well, I have somehow managed to do it even though it probably isn't the best way. It works though and my main focus is not the backend, so I guess it's good enough

In redux toolkit query:

    endpoints: (builder) => ({
    getAllProducts: builder.query({
        query: (page = 1) => `${baseUrl}?page=${page}`,
    }),

In my index.js

const router = useRouter();
const [page, setPage] = useState(1);
const { data, isLoading, error } = useGetAllProductsQuery(page);

const handlePaginationChange = (e, value) => {
    e.preventDefault();
    setPage(value);
    router.push(`/products?page=${value}`);
};

and my API route:

 const handler = nc().use(Cors());
handler.get(async (req, res) => {
    await db.connect();
    const products = await Product.paginate({}, { page: req.query.page, limit: 9 });
    res.send(products);
});
  • Related