本文介绍了刷新页面后Next.js 404错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to learn Next.js but I have a small problem.Here is my test code:

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 页面点击链接关于,我的 url 看起来 '/about/1/' 并且工作正常,但如果我刷新页面我得到错误 404.如果我输入浏览器 /abouts?id=2" 并刷新页面一切正常.你知道我该如何解决这个问题吗?我想要像

If I clicked in link About from index.js page, my url look '/about/1/' and work fine, but if I refresh page I get error 404. If I type in browser /abouts?id=2" and refresh page everything works fine. Do u know how I can fix this ?I want have links like

/about/1/

推荐答案

来自 下一步.js 文档:

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

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

So to achieve this behavior, you'll need to configure custom routes inside your server.js—for example using express. Extend your server with this:

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}`);
  });
});

这篇关于刷新页面后Next.js 404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 03:28