英文:
Passing query id in api request send undefined id while refrshing page
问题
In your Next.js code, you are trying to fetch the value of a particular blog's ID from the API request using router.query.id
. However, you mentioned that you are getting undefined
when the page is refreshed on the server side (Node.js).
在你的Next.js代码中,你试图通过router.query.id
从API请求中获取特定博客的ID值。然而,你提到在服务器端(Node.js)刷新页面时得到的是undefined
。
To solve this problem, you can check if router.query.id
is available before making the API request. If it's undefined
on the server side, it might be due to server-side rendering (SSR) behavior. You can use Next.js's getServerSideProps
to fetch data on the server side and pass it as props to your component. This way, you ensure that the ID is available even on the server side.
要解决这个问题,你可以在进行API请求之前检查router.query.id
是否可用。如果在服务器端是undefined
,那可能是因为服务器端渲染(SSR)的行为。你可以使用Next.js的getServerSideProps
在服务器端获取数据,并将其作为props传递给你的组件。这样,你可以确保ID在服务器端也是可用的。
英文:
> In nextJs,I am making blog web apps. I want to get value of particular blog passing an id in api request.
const ViewDetail = () => {
const[categoriesData,setCategoriesData]=useState([]);
const router=useRouter();
const fetchCategoreis=async()=>{
const res=await fetch(`http://localhost:4000/blogs/${router.query.id}`)
const data=await res.json();
setCategoriesData(data.dataById)
}
useEffect(()=>{
fetchCategoreis();
},[])
return (
<>
<Box>
<Image src={`/uploads/${categoriesData.pic}`}/>
<Title>{categoriesData.title}</Title>
<Author>Author:<span> </span><p style={{fontWeight:600,display:"inline-block"}}>{categoriesData.username}</p></Author>
<Typography>{categoriesData.description}</Typography>
</Box>
</>
)
}
While I refresh page I get undefined value of req.params.id on server side(node js)
const getByIDBlogController=async(req,res)=>{
console.log(req.params.id)
}
**output on server <br/>
req.params.id value 64903e9170559406037885ed <br/>
req.params.id value undefined <br/>
req.params.id value undefined <br/>
**
I want to get only id of particular blog but am getting undefined of params(id) when page is refreshed.How do I slove this problem.
答案1
得分: 1
使用条件更新此代码
useEffect(()=>{
获取类别();
},[])
// 更新后的代码
useEffect(()=>{
if( router?.query?.id !== 'undefined' && categoriesData === [] ) {
获取类别();
}
},[]) // 在这里添加其余的依赖
这是解决此错误的最简单方法
有很多方法,但这是最简单/最懒的方法
英文:
Update This Code With Some Condition
useEffect(()=>{
fetchCategoreis();
},[])
// Updated Code
useEffect(()=>{
if( router?.query?.id !== 'undefined' && categoriesData === [] ) {
fetchCategoreis();
}
},[]) // Add Rest Dependency Here
It Is Most Easy Way To Resolve This Error
And There Is So Many Way But it Is Easiest/Laziest one
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论