如何从 NextJS 的 public 文件夹中获取()?

How to fetch() from public folder in NextJS?

我有以下用例场景。我有网络工作者,我需要在其中获取位于 NextJS public 文件夹中的图像,以便将其转换为 blob。

现在执行 fetch('public/images/myImage.png');fetch('/images/myImage.png'); 会导致错误:

Error: TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Failed to parse URL from /images/ui/background_fire.jpg

所以我假设它没有像说 src 图片那样被正确解析?

根据official Docs you need to use isomorphic-unfetch.

It's a simple implementation of the browser fetch API, but works both in client and server environments.

安装它

$npm install --save isomorphic-unfetch

$yarn add isomorphic-unfetch

现在您可以在 getInitialProps 到组件中的任何地方使用它。

示例::

`import fetch from 'isomorphic-unfetch';`

// ... Index component code

Index.getInitialProps = async function() { 

  const res = await fetch('https://api.tvmaze.com/search/shows?q=batman');
  const data = await res.json();
    
  console.log(`Show data fetched. Count: ${data.length}`);
    
  return {
    shows: data.map(entry => entry.show)
  };
};

编码愉快!!

@NasiruddinSaiyed 的回答有点过时,所以这是 2021 年的回答:

NextJS server-side-polyfills docs

Server-Side Polyfills

In addition to fetch() on the client side, Next.js polyfills fetch() in the Node.js environment. You can use fetch() on your server code (such as getStaticProps) without using polyfills such as isomorphic-unfetch or node-fetch.

所以它应该开箱即用