简体   繁体   English

所有预加载链接的 Next.js 404 错误

[英]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.我是 next.js 的新手,作为第一步,在我开始开发实际的应用程序之前,我正在按照文档学习基础知识,现在,我正在努力让预取工作,因为所有预加载的请求返回 404 错误。

So what's wrong with my code?那么我的代码有什么问题呢? How can I solve this problem?我怎么解决这个问题?

The demo repository is on github .演示存储库位于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).请注意,只有express服务器知道如何处理这种/post/:id URL, next.js不知道它,因此next.js尝试预取不存在的页面(您可能会在 Chrome 控制台输出中看到)。

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.因此,只会执行一个预取post.js页面的查询。 在此处输入图像描述

This technique is called "route masking" you may read more about in in the Next.js tutorial这种技术称为“路由屏蔽”,您可以在Next.js 教程中了解更多信息

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.更新:问题似乎更多是关于prefetch功能在 Next.js 中的实际工作方式,因此我将尝试对其进行解释。 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.如果链接上没有prefetch属性,Next.js 将按需加载相关块(当用户单击链接时),因此加载和解析 javascript 会导致小的延迟。 The prefetch prop allows you to remove this delay because javascript will be loaded as soon as possible after application start. prefetch属性允许您消除此延迟,因为 javascript 将在应用程序启动后尽快加载。 In both cases new page will be rendered in the browser like in a usual React app.在这两种情况下,新页面都将像在通常的 React 应用程序中一样在浏览器中呈现。

Don't use this: import Link from "next/link";不要使用这个: import Link from "next/link";

Use: import { Link } from './routes';使用: import { Link } from './routes'; This is the routes.js configuration file这是 routes.js 配置文件

My routes.js:我的路线.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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