简体   繁体   中英

Next.js 404 error for all preloaded links

I'm new to next.js and as a first step, before I start developing the actual app, I'm following the docs to learn the basics, and right now, I'm struggled trying to get the prefetch working, since all the preloaded requests are returning 404 error.

So what's wrong with my code? How can I solve this problem?

The demo repository is on github .

在此处输入图像描述

Notice that only express server knows how to process URL of this kind /post/:id , next.js doesn't know it so next.js tries to prefetch unexistent pages (and you may see in the Chrome console output).

You may fix this behaviour easily: just need rewrite your links this way

<Link href={`/post/?id=${show.id}`} as={`/post/${show.id}`} prefetch>

As a result only one query to prefetch post.js page will be executed. 在此处输入图像描述

This technique is called "route masking" you may read more about in in the Next.js tutorial

An update: It seems that the question is more about how prefetch feature actually works in Next.js so I will try to explain it. Without prefetch prop on the Link Next.js will load related chunk on demand (when a user clicks link) so it will cause a small delay to load and parse javascript. The prefetch prop allows you to remove this delay because javascript will be loaded as soon as possible after application start. In both cases new page will be rendered in the browser like in a usual React app.

Don't use this: import Link from "next/link";

Use: import { Link } from './routes'; This is the routes.js configuration file

My routes.js:


const routes = (module.exports = require("next-routes")());
routes.add("/:username", "profilepage");

Using:

import { Link } from './routes';
<Link route={"/my_page"}><a href="my_page">My Page</a></Link>

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