无法在NextJS中的服务器端提取查询字符串

tcbh2hod  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(106)

我使用NextJS应用程序目录结构进行路由。
/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;
  • 在上面的代码中,我已经使用SearchParams在客户端获取了查询字符串,并将其传递给参数中的函数,该参数用于在axios中作为URL传递。
  • 到目前为止,数据被正确显示,但它不会在服务器端传递。
  • 这里是/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});
  }
};
  • 在这里,我已经控制了req.query,但它显示为undefined。
  • 我不能使用useRouter(),searchParams或服务器端的任何东西,我只是想在可能的情况下使用request获取查询参数。
ncecgwcz

ncecgwcz1#

看起来req.query在较新版本的app目录中不存在。试试这个:

export async function GET(req: Request) {

   const url = new URL(req.url)
   const rating=url.searchParams.get('rating')
}

相关问题