所有预加载的链接的Next.js 404错误 [英] Next.js 404 error for all preloaded links

查看:59
本文介绍了所有预加载的链接的Next.js 404错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是next.js的新手,第一步,在开始开发实际应用之前,我正在关注文档以学习基础知识,而现在,我正努力尝试使预取工作正常进行,因为所有预加载的请求都返回404错误.

那么我的代码有什么问题?我该如何解决这个问题?

演示存储库位于

解决方案

注意,只有 express 服务器知道如何处理/post/:id 这种URL, next.js 不知道,所以 next.js 会尝试预取不存在的页面(您可能会在Chrome控制台输出中看到).

您可以轻松解决此问题:只需以这种方式重写链接

 <代码><链接href = {`/post/?id = $ {show.id}`} as = {`/post/$ {show.id}`}预取> 

因此,将仅执行一个查询以预取 post.js 页面.

这种技术称为路由屏蔽",您可以在 Next.js教程

更新:似乎问题更多是关于 prefetch 功能在Next.js中如何实际起作用,因此我将尝试对其进行解释.在链接上没有 prefetch 道具的情况下,Next.js将按需加载相关的块(当用户单击链接时),因此加载和解析javascript时会产生少量延迟. prefetch 道具可让您消除此延迟,因为在应用程序启动后将尽快加载javascript.在这两种情况下,新页面都将像通常的React应用程序一样在浏览器中呈现.

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.

这篇关于所有预加载的链接的Next.js 404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆