ran*_*its 17 javascript reactjs next.js
如果请求的页面没有底层服务器端资源,我正在服务器端呈现的页面中寻找处理 HTTP 404 的最佳实践。
例如,假设请求的页面是http://localhost:3000/places/5
。在我的 SSG 实施中:
export async function getServerSideProps(context) {
const placeId = context.params.placeId;
const places = await getPlace(placeId);
if (!places.length) { /* is there anything here I can do to facilitate a 404? this place does not exist in the db */ }
return {
props: {
places[0],
},
};
}
Run Code Online (Sandbox Code Playgroud)
这应该是不言自明的,但如果在这种情况下请求的 id5
不在我的数据库中,我该如何将其作为 HTTP 404 处理?
You*_*mar 43
您可以通过返回一个对象来做到这一点,如下面的代码所示,带有notFound: true
. 这是官方文档的引用:
布尔
notFound
值允许页面返回404
状态和404
页面。
export async function getServerSideProps(context) {
const placeId = context.params.placeId;
const places = await getPlace(placeId);
if (!places.length) {
return {
notFound: true,
}
}
return {
props: {
places[0],
},
};
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20177 次 |
最近记录: |