繁体   English   中英

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

[英]How to fetch() from public folder in NextJS?

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

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

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

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

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

NextJS 服务器端 polyfills 文档

服务器端 Polyfill

除了客户端的 fetch() 之外,Next.js 还填充了 Node.js 环境中的 fetch()。 您可以在服务器代码(例如 getStaticProps)上使用 fetch(),而无需使用诸如 isomorphic-unfetch 或 node-fetch 之类的 polyfill。

所以它应该开箱即用

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

快乐编码!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM