具有_error的Next.js动态URL

[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

Hearbirds 回答:具有_error的Next.js动态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('*',res) => {
    return handle(req,res)
  })

  server.listen(port,err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})
本文链接:https://www.f2er.com/3154830.html

大家都在问