Next.js Dynamic URL with _error



[id].tsx

const Home:NextPage<any> = (props) => {
return (
<div>
{JSON.stringify(props)}
</div>
)
}
Home.getInitialProps = async (props) => {
// getting data from Database if we have an item which matched props.query.id;
const response = await axios.get('https://MY_API.com/'+props.query.id);''
// response format is like this
/*
response: {
status: 200 | 500,
item: Item | undefined
}
*/
//If response has no item, I would like to show _error.tsx instead [id].tsx
return { ...props, response };
}
export default Home;

_error.tsx

const Error:NextPage<any> = (props) => {
return <div>ERROR PAGE</div>
}
export default Error;

我找到了一个解决方案,它重定向到/_error,但我不想更改URL

localhost:3000/EXIST_ID=>显示[id].tsx并保持URL

localhost:3000/NOT_EXIST_ID=>显示_error.tsx并保持URL

您将需要使用自定义服务器,并在id不存在时呈现"错误"页面。

const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.get('/:id', (req, res) => {
const page = IS_ID_EXISTS? '/posts' : '/_error';
return app.render(req, res, page, { id: req.params.id })
})
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})

最新更新