我正试图解决我们的网络应用程序的一个具体要求。我们有一个页面‘项目’,如果一个项目出售,应该继续显示项目,但页面的响应代码必须设置为404。我在尝试这样的方法:
在第/id/Item.tsx页中:
static async getInitialProps(ctx) {
//retrieve item
if (item.isSoldOut) {
ctx.res.statusCode = 404;
}
//all other stuff
}
但是它将自动重定向到状态代码302的主页。如何实现这种行为?
发布于 2020-10-14 07:40:38
Next.js文档建议使用getStaticProps
或getServerSideProps
代替getInitialProps
(https://nextjs.org/docs/api-reference/data-fetching/getInitialProps)
使用getServerSideProps
,您可以如下所示
export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
res.statusCode = 404;
return { props: {} }
}
使用getInitialProps
,您可以这样做:
static async getInitialProps({res}) {
// server side
if(res) res.statusCode = 404;
// client side
return { statusCode : 404 }
}
https://stackoverflow.com/questions/64347721
复制相似问题