最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Next.js 404 error for all preloaded links - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Apr 28, 2019 at 5:33 Lucas SilvaLucas Silva 1,4111 gold badge14 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10 +50

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>
发布评论

评论列表(0)

  1. 暂无评论