网站搜索

javascript - 如何在 NextJS 中从 public 文件夹使用 fetch()?


我有以下使用场景。我有一个 web worker,在其中我需要获取位于 NextJS public 文件夹中的图像,以便将其转换为 blob。

目前执行 fetch('public/images/myImage.png'); 或 fetch('/images/myImage.png'); 会导致错误:

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

所以我假设它没有像在图片的 src 中那样被正确解析,对吗?

答案#1

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

NextJS 服务器端 polyfills 文档

服务器端填充

除了在客户端使用 fetch() 外,Next.js 还在 Node.js 环境中对 fetch() 进行了 polyfill。您可以在服务器代码(例如 getStaticProps)中使用 fetch(),而无需使用 isomorphic-unfetch 或 node-fetch 等 polyfill。

所以它应该开箱即用

答案#2

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

编码愉快!!