简体   繁体   中英

Next.js 404 error after refreshing the page

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>
)

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/

From the Next.js documentation :

The second as parameter for push and replace is an optional decoration of the URL. Useful if you configured custom routes on the server.

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

Puedes usar un archivo .htaccess, por ejemplo para un dominio xyz.com donde se creo un portal con nextjs puedes usar este archivo:

  RewriteEngine On  
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^ - [L]

  RewriteRule ^ /index.html [L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM