[英]next js react app fetch not defined error
I am trying to clone the following next.js react app and run it on localhost:3000我正在尝试克隆以下 next.js react 应用程序并在 localhost:3000 上运行它
https://github.com/elee-ittdublin/lab6-nextjs https://github.com/elee-ittdublin/lab6-nextjs
when I open localhost:3000 I get the following error当我打开 localhost:3000 时,出现以下错误
Unhandled Rejection (ReferenceError): fetch is not defined Function._callee$ ./pages/index.js:22未处理的拒绝(ReferenceError):fetch 未定义 Function._callee$ ./pages/index.js:22
20 | // see https://nextjs.org/learn/basics/fetching-data-for-pages
>22 | Index.getInitialProps = async function() {
24 | const url = 'https://api.tvmaze.com/search/shows?q=batman';
I have tried to research what I am doing wrong but I still can not fix my problem.我试图研究我做错了什么,但我仍然无法解决我的问题。 Can anyone see where I am going wrong?
谁能看到我哪里出错了?
Cheers干杯
If you go to the examples here examples and search for fetch
, you will see what they are using.如果您转到示例此处的示例并搜索
fetch
,您将看到它们正在使用什么。 In the examples is node-fetch
- node-fetch在示例中是
node-fetch
- node-fetch
May be the package is not installed.可能是没有安装包。 Try installing https://www.npmjs.com/package/isomorphic-unfetch
尝试安装https://www.npmjs.com/package/isomorphic-unfetch
fetch
is a predefined method in the browser but your function works in server side, so it does not work. fetch
是浏览器中的预定义方法,但您的功能在服务器端工作,因此它不起作用。
There is an npm package that basically combines browser's fetch and node-fetch together, it is named isomorphic-unfetch, you can install it via the command npm install isomorphic-unfetch
.有一个 npm 包,基本上将浏览器的 fetch 和 node-fetch 结合在一起,它被命名为 isomorphic-unfetch,你可以通过命令
npm install isomorphic-unfetch
安装它。
After that use unfetch
method anywhere u want to use fetch
method.之后在任何你想使用
fetch
方法的地方使用unfetch
方法。
PS: In the newer versions of Next.JS ( 10.0.0 and above ) you should not see this problem. PS:在较新版本的 Next.JS(10.0.0 及以上)中,您应该不会看到这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.