[英]How to fetch() from public folder in NextJS?
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.我有网络工作者,我需要在其中获取位于 NextJS
public
文件夹中的图像,以便将其转换为 blob。
Right now executing fetch('public/images/myImage.png');
现在执行
fetch('public/images/myImage.png');
or fetch('/images/myImage.png');
或
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
错误:TypeError:无法在“WorkerGlobalScope”上执行“fetch”:无法从 /images/ui/background_fire.jpg 解析 URL
So I assume it is not being resolved correctly like it would in say src
of an image?所以我认为它没有像在图像的
src
中那样正确解析?
@NasiruddinSaiyed answer is a bit outdated so here is the 2021 answer: @NasiruddinSaiyed 的回答有点过时了,所以这里是 2021 年的回答:
NextJS server-side-polyfills docs NextJS 服务器端 polyfills 文档
Server-Side Polyfills
服务器端 Polyfill
In addition to fetch() on the client side, Next.js polyfills fetch() in the Node.js environment.
除了客户端的 fetch() 之外,Next.js 还填充了 Node.js 环境中的 fetch()。 You can use fetch() on your server code (such as getStaticProps) without using polyfills such as isomorphic-unfetch or node-fetch.
您可以在服务器代码(例如 getStaticProps)上使用 fetch(),而无需使用诸如 isomorphic-unfetch 或 node-fetch 之类的 polyfill。
So it should just work out of the box所以它应该开箱即用
As per official Docs you need to use isomorphic-unfetch .根据官方文档,您需要使用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
$
npm install --save isomorphic-unfetch
or或者
$ yarn add isomorphic-unfetch
$
yarn add isomorphic-unfetch
Now you can use it in from getInitialProps
to any where in your component.现在,您可以在
getInitialProps
到组件中的任何位置使用它。
Example ::例子 ::
`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)
};
};
Happy coding!!快乐编码!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.