admin管理员组文章数量:1394979
I' trying to use fetch to access data in other file but it keeps return
ReferenceError: fetch is not defined
const getData = async () => {
const fetchedData = await fetch("./dino.json");
const data = await fetchedData.json();
return data.Dinos;
};
getData().then(data => {
console.log(data); // will print the array
}).catch(error => {
console.error(error);
});
I am looking at this fetch API but it did not specify that if we need install anything
I' trying to use fetch to access data in other file but it keeps return
ReferenceError: fetch is not defined
const getData = async () => {
const fetchedData = await fetch("./dino.json");
const data = await fetchedData.json();
return data.Dinos;
};
getData().then(data => {
console.log(data); // will print the array
}).catch(error => {
console.error(error);
});
I am looking at this fetch API but it did not specify that if we need install anything
Share Improve this question asked Mar 23, 2021 at 4:46 Tony LiTony Li 311 gold badge1 silver badge4 bronze badges 1- Does this answer your question? ReferenceError: fetch is not defined – Phoenix Commented Mar 23, 2021 at 4:52
4 Answers
Reset to default 3You are probably using node
where fetch
is not defined, it's only available by default in a browser. U can install it as a npm
package node-fetch.
As Marcos said, If you are using a node
, the fetch method will not be available. And to use it, you need to install the "node-fetch" package and then import to use it.
After using "node-fetch", you'll get another error " Only absolute URLs are supported"
, to fix that, you need to give the full URL of the file.
Here is the example code:
import fetch from 'node-fetch'
const getData = async () => {
const fetchedData = await fetch("http://localhost:3000/dino.json");
const data = await fetchedData.json();
return data.Dinos;
};
If you upgrade from Node.js 18 or higher, you won't get the error anymore. The versions include an experimental globally available Fetch API. See the Node.js documentation for more details.
Sometimes this happens because you are using a node version older than 18 which doesn't include "fetch".
You can either install the dependency as stated in other responses or update your node version.
本文标签: javascriptfetch is not defined when access another fileStack Overflow
版权声明:本文标题:javascript - fetch is not defined when access another file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744106262a2591077.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论