【发布时间】:2021-06-28 20:20:20
【问题描述】:
我有下一个应用程序。当 [slug] 页面中的路由不匹配时,我需要实现逻辑然后显示 404 页面错误。
据我所知,在接下来的显示 404 页面中,我需要返回值为 true.Link 的 notFound 对象
所以问题是当我从getServerSideProps 返回{ notFound: true } 时为什么会出现这个错误?
错误:从
getServerSideProps返回了其他密钥。 用于您的组件的属性必须嵌套在props键,例如:return { props: { title: 'My Title', content: '...' } }
需要移动的键:notFound.
代码:
export const getServerSideProps: GetServerSideProps = async ({ params, req }) => {
const { slug } = params;
// first request
const data = await (await fetch(`${process.env.NEXT_PUBLIC_API_HOST}/${slug}`)).json();
// second request
const user = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}`, {
method: "GET",
headers: {
'Authorization': 'Bearer ' + "jwt",
'Content-Type': 'application/json',
},
});
const userInfo = await user.json();
if ( !slug || data.statusCode === 404 ) return { notFound: true }
return {
props: {
title: "something",
// my props in here
},
}
}
只有当我在url 中写一些东西并有意识地将我的 slug 页面从正确更改为不正确时,它才会出错。例如从localhost/page/1 到localhost/page/blablabla。
在这种情况下,当我将路线更改为错误时,如果情况 (if ( !slug || data.statusCode === 404 ) ).Next 版本 9.5.2,则可以这样做
【问题讨论】:
-
你确定这是给你一个错误的代码吗?它看起来不错,除了奇怪的等待,但它应该按预期工作。您使用的是哪个版本的 Next?
-
@Danila 只有当我在 url 中写一些东西并有意识地将我的 slug 页面从正确更改为不正确时,它才会出错。例如从
localhost/page/1到localhost/page/blablabla。在这种情况下,当我将路由更改为错误时,如果情况(if ( !slug || data.statusCode === 404 ) ). 下一个版本9.5.2。更新答案