TypeError:Cannot read properties of undefined(阅读'limit')using nextjs 13

ig9co6j1  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(228)

错误类型错误:
在获取API时,我没有从api调用中获取任何值。

Cannot read properties of undefined (reading 'limit')
    at GET (webpack-internal:///(sc_server)/./app/api/prompt/route.js:10:11)
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:242:43)
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/lib/trace/tracer.js:111:36)
    at NoopContextManager.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:360:30)
    at ContextAPI.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:30:58)
    at NoopTracer.startActiveSpan (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:953:34)
    at ProxyTracer.startActiveSpan (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:993:36)
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/lib/trace/tracer.js:100:107)

在API router.js文件中:

export const GET = async (req) => {
  let { limit = 3, skip = 0 } = req.query
  console.log(limit, skip)

  try {
    await connectToDB()
    const prompts = await Prompt.find({})
      .populate('creator')
      .limit(Number(limit))
      .skip(Number(skip))
    return new Response(JSON.stringify(prompts), { status: 200 })
  } catch (error) {
    return new Response('Failed to fetch prompt', { status: 500 })
  }
}

API fetch:使用效果:
其中limit= 3,skip= 0

useEffect(() => {
    const fetchlimitPosts = async () => {
      try {
        const response = await fetch(
          `/api/prompt?limit=${limit}&skip=${skip}`
        )

        if (!response.ok) {
          throw new Error('Failed to fetch limit posts')
        }

        const data = await response.json()
        setPosts(data)
      } catch (error) {
        console.error(error)
        setPosts([])
      }
    }

    fetchlimitPosts()
  }, [skip])

如何提取route.jsapp/API文件夹中的limit和skip值。

bfrts1fy

bfrts1fy1#

解决方案如下:

export const GET = async (req) => {
  let limit = req.nextUrl.searchParams.get('limit')
  let skip = req.nextUrl.searchParams.get('skip')
  console.log(limit, skip)

  try {
    await connectToDB()
    const prompts = await Prompt.find({})
      .populate('creator')
      .limit(Number(limit))
      .skip(Number(skip))
    return new Response(JSON.stringify(prompts), { status: 200 })
  } catch (error) {
    return new Response('Failed to fetch prompt', { status: 500 })
  }
}

相关问题