错误类型错误:
在获取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值。
1条答案
按热度按时间bfrts1fy1#
解决方案如下: