如何从 NextJS 中的公共文件夹中 fetch() ?

Ilj*_*lja 5 javascript web-worker reactjs webpack next.js

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

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

错误:TypeError:无法在“WorkerGlobalScope”上执行“fetch”:无法从 /images/ui/background_fire.jpg 解析 URL

所以我认为它没有像src图像那样被正确解析?

Nas*_*yed 1

根据官方文档,您需要使用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)
  };
};

Run Code Online (Sandbox Code Playgroud)

快乐编码!!