我如何得到请求.查询nextjs api?



我有这个API,我正试图获得我在URL中传递的查询(例如products?page=1&limit=10),但我一直得到一个空对象

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;
console.log(req.query.page, req.query.limit)

你可以将任何props传递给你的api

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

嗯,我已经设法做到了,尽管这可能不是最好的方法。它的工作虽然,我的主要焦点不是后端,所以我想这是足够好的

在redux toolkit查询中:

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}`);
};

和API路由:

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);
});

最新更新