【问题标题】:Next.js 404 error after refreshing the pageNext.js 刷新页面后出现404错误
【发布时间】:2018-04-03 03:54:33
【问题描述】:

我尝试学习 Next.js,但我遇到了一个小问题。 这是我的测试代码:

import Link from 'next/link';
export default () => (
    <p>Hallo next <Link href="/abouts?id=2" as='/abouts/1'><a>About</a></Link></p>
)

如果我单击 index.js 页面中的 About 链接,我的 url 看起来 '/about/1/' 并且工作正常,但如果我刷新页面,我会收到错误 404。如果我在浏览器中输入 /abouts?id=2" 并刷新页面,一切正常。你知道我该如何解决这个问题吗? 我想要像

这样的链接
/about/1/

【问题讨论】:

    标签: reactjs routes next.js


    【解决方案1】:

    来自Next.js documentation

    pushreplace 的第二个 as 参数是 URL 的可选装饰。如果您在服务器上配置了自定义路由,则很有用。

    因此,要实现此行为,您需要在 server.js 中配置自定义路由,例如使用 express。用这个扩展你的服务器:

    const next = require('next');
    const express = require('express');
    
    const dev = process.env.NODE_ENV !== 'production'
    const app = next({ dev });
    const handle = app.getRequestHandler();
    
    app.prepare().then(() => {
      const server = express();
    
      // Nice permalinks for pages.
      // Sets up a custom route, that then uses next.js to render the about page.
      server.get('/about/:id', (req, res) => {
        const params = { id: req.params.id };
        return app.render(req, res, '/about', params);
      });
    
      // For all other routes, use next.js.
      server.get('*', (req, res) => {
        return handle(req, res);
      });
    
      server.listen(port, '0.0.0.0', err => {
        if (err) throw err;
        console.log(`${'\u2705'}  Ready on http://localhost:${port}`);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-23
      • 2022-12-09
      • 1970-01-01
      • 2021-05-11
      • 2012-10-24
      • 2023-01-26
      • 1970-01-01
      • 2015-04-21
      相关资源
      最近更新 更多