我有一个动态页面,它显示了产品的详细信息,如果找不到所请求的产品,外部服务器将返回404,问题是getServerSideProps显示了一个空白页,而不是重定向到404。
以下是代码:
// pages/[slug].tsx
export const getServerSideProps: GetServerSideProps = async ({
params,
res,
}) => {
const { product, relatedProducts } = await getProductDetail(
params?.slug as string
);
if (res.statusCode === 404) {
return {
redirect: { destination: "/404", permanent: false },
};
}
return {
props: {
product,
relatedProducts,
},
};
};
我还尝试使用notFound
属性
if (res.statusCode === 404) {
return {
notFound: true
};
}
这是我第一次遇到这个问题,因为服务器重定向在其他(静态)页面中运行得很好。
我们非常感谢你的帮助。
发布于 2022-10-29 18:01:34
从NextJS 10开始,您不必显式地返回您的404页,这要归功于新的标志notFound: true。您可以在getStaticProps和getServerSideProps上使用它自动触发默认的404页或您自己的自定义404页。
// pages/[slug].tsx
export const getServerSideProps: GetServerSideProps = async ({
params,
res,
}) => {
const { product, relatedProducts } = await getProductDetail(
params?.slug as string
);
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
// if (res.statusCode === 404) {
// return {
// redirect: { destination: "/404", permanent: false },
// };
// }
return {
props: {
product,
relatedProducts,
},
};
};
文档引用
https://stackoverflow.com/questions/74247455
复制相似问题