最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to fetch() from public folder in NextJS? - Stack Overflow

programmeradmin1浏览0评论

I've got following use case scenario. I have web worker within which I need to fetch image that is located in NextJS public folder in order to convert it to blob.

Right now executing fetch('public/images/myImage.png'); or fetch('/images/myImage.png'); leads to an error:

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

So I assume it is not being resolved correctly like it would in say src of an image?

I've got following use case scenario. I have web worker within which I need to fetch image that is located in NextJS public folder in order to convert it to blob.

Right now executing fetch('public/images/myImage.png'); or fetch('/images/myImage.png'); leads to an error:

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

So I assume it is not being resolved correctly like it would in say src of an image?

Share Improve this question asked Nov 26, 2019 at 11:00 IljaIlja 46.5k103 gold badges289 silver badges527 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

@NasiruddinSaiyed answer is a bit outdated so here is the 2021 answer:

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.

So it should just work out of the box

As per 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.

Install it

$npm install --save isomorphic-unfetch

or

$yarn add isomorphic-unfetch

Now you can use it in from getInitialProps to any where in your ponent.

Example ::

`import fetch from 'isomorphic-unfetch';`

// ... Index ponent code

Index.getInitialProps = async function() { 

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

Happy coding!!

发布评论

评论列表(0)

  1. 暂无评论