Home > Enterprise >  Using node-fetch in React app - "Cannot find module 'node:http'"
Using node-fetch in React app - "Cannot find module 'node:http'"

Time:03-30

I have a simple setup with Strapi as a backend and React as a frontend. My goal is to get the result from the api I have in my backend using any tool out there. I first tried with Axios but seems to have an issue doing GET call because the 'Content-Lenght' wasn't generated automatically and I couldn't set it manually somehow.

I decided to use something else and one that I found that seems popular is node-fetch.

However, I can't even begin to use it. I install it locally to my project using:

npm i node-fetch --save

Then in my .js file:

import fetch from 'node-fetch';

const App = () => {
    const result = fetch('https://api.github.com/');
}

export default App;

Then I try compiling or running the project and I get the following error message:

.\node_modules\node-fetch\src\index.js
Cannot find module: 'node:http'. Make sure this package is installed.

If I check the actual file in the node-fetch module. It is easy to see that the said module is imported there. However, I am unsure what this format for importing is even about with the 'node:xxxx'. I supose this is some kind of way to import basic node module but then, why would they be missing from my installation.

I tried it on me personal dev PC first and it failed. I then went ahead and troubleshooted for hours as to what it could be. I ended cleaning my entire project node_modules, rebuilding, uninstalling node.js and everything module installed globally. Reinstalling through nvm instead. Still didn't work.

I also tried installing "npm i http --save", which did nothing.

and today, I just tried this on a fresh project on my work computer and I have the exact same thing.

what could it be? Is this just a node-fetch issue in general?

("node-fetch": "^3.2.3")

CodePudding user response:

The package node-fetch is a fetch implementation for Node.js not for the browser. In React you should be able to use fetch without installing and importing any package because fetch is part of the browser API and is present on the window object (window.fetch).

For browsers that don't support fetch you need a polyfill, check Can I Use for browser support and use whatwg-fetch as a polyfill.

See this for a polyfill solution for CRA: https://github.com/facebook/create-react-app/blob/main/packages/react-app-polyfill/README.md

See this for examples on how to use fetch in React: https://reactjs.org/docs/faq-ajax.html

  • Related