【问题标题】:How to fetch() from public folder in NextJS?如何从 NextJS 的公用文件夹中获取()?
【发布时间】:2020-03-21 18:50:23
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript reactjs webpack next.js web-worker


    【解决方案1】:

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

    NextJS server-side-polyfills docs

    服务器端 Polyfills

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

    所以它应该开箱即用

    【讨论】:

      【解决方案2】:

      根据official Docs,您需要使用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)
        };
      };
      
      

      编码愉快!!

      【讨论】:

        猜你喜欢
        • 2022-07-28
        • 2019-06-23
        • 2021-10-08
        • 2014-03-21
        • 2021-12-03
        • 1970-01-01
        • 2014-11-09
        • 1970-01-01
        • 2016-09-03
        相关资源
        最近更新 更多