【问题标题】:Next.js Dynamic URL with _errorNext.js 带有 _error 的动态 URL
【发布时间】:2019-11-06 14:28:27
【问题描述】:

[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

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    您将需要使用自定义服务器,并在 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}`)
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2020-09-08
      • 2021-11-02
      • 2021-12-18
      • 1970-01-01
      • 2021-10-12
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多