Ilj*_*lja 5 javascript web-worker reactjs webpack next.js
我有以下用例场景。我有一个网络工作者,我需要在其中获取位于 NextJSpublic
文件夹中的图像,以便将其转换为 blob。
现在执行fetch('public/images/myImage.png');
或fetch('/images/myImage.png');
导致错误:
错误:TypeError:无法在“WorkerGlobalScope”上执行“fetch”:无法从 /images/ui/background_fire.jpg 解析 URL
所以我认为它没有像src
图像那样被正确解析?
根据官方文档,您需要使用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)
};
};
Run Code Online (Sandbox Code Playgroud)
快乐编码!!
归档时间: |
|
查看次数: |
4315 次 |
最近记录: |