I'm using NextJS app directory structure for routing.
/app/page.jsx
import ListProduct from "@components/products/ListProduct";
import axios from "axios";
const getProducts = async (min, max, category, rating) => {
console.log(min,max,category,rating)
const {data} = await axios.get(
`${process.env.AXIOS_URL}/api/products?min=${min}&max=${max}&category=${category}&rating=${rating}`
);
return data;
};
const Home = async ({searchParams}) => {
const min = searchParams.min || "";
const max = searchParams.max || "";
const category = searchParams.category || "";
const rating = searchParams.rating || "";
const products = await getProducts(min, max, category, rating);
//Filtering of data.
return <ListProduct data={products} />;
};
export default Home;
in above code I have fetched the query string on client side using SearchParams and passed to function in parameter which is being used to pass as URL in axios.
till now data is being properly showed but it won't passed in server side.
here is the /app/api/products/route.js
import Product from "@backend/models/product";
import {connectToDB} from "@backend/utils/connectToDB";
export const POST = async (request) => {
try {
await connectToDB();
const data = await request.json();
const newProduct = new Product(data);
await newProduct.save();
return new Response(JSON.stringify(newProduct), {status: 201});
} catch (error) {
console.log(error);
return new Response(error, {status: 500});
}
};
export const GET = **async (req, res)** => {
try {
**console.log(req.query);**
await connectToDB();
const data = await Product.find({});
return new Response(
JSON.stringify({
data: data,
message: "Products fetched successfully",
}),
{status: 201}
);
} catch (error) {
return new Response("Failed to fetch a Product", {status: 500});
}
};
here i have consoled req.query but it's showing me undefined.
I can't use useRouter(), searchParams or anything on server side , I just want to get the query params using request if possible.
Looks like req.query
does not exist in newer versions of app
directory. try this:
export async function GET(req: Request) {
const url = new URL(req.url)
const rating=url.searchParams.get('rating')
}