DEV Community

AquaCat
AquaCat

Posted on

1

【Node.js】How to fix the error "fetch is not defined"

Version of node.js...v14.15.4

PROBLEM

When I executed query in Apollo Server, I encountered this error message from the server.

"errors": [
    {
      "message": "fetch is not defined",
      "locations": [
        {
          "line": 3,
          "column": 1
        }........
Enter fullscreen mode Exit fullscreen mode

What does this mean? "fetch" is a method that handles request and response in asynchronous communication. Looks like this method is causing this error message.

const resolvers = {
    Query: {
        singlePokemon:async(parent, args) => {
      let res = await fetch(`https://pokeapi.co/api/v2/pokemon/${args.id}`);
Enter fullscreen mode Exit fullscreen mode

SOLUTION

The version of Node before 18 does not have the fetch API. So, you need to install an external module.
https://www.npmjs.com/package/node-fetch

npm install node-fetch
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay