-1

I have gone three many documentations and other sources yet I can’t fix my error. I have just learning JavaScript and I’m trying out fetch() commands but I can’t get passed this error(the title)

Here is my code

index.js

import fetch from 'node-fetch';

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));


package.json

{
  "name": "Weather-API",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "node-fetch": "^3.0.0"
  }
}
Makashi
  • 15
  • 4
  • 1
    Which node version do you have? Type `node -v` at the command prompt. I have v16.3 and the code works fine for me. –  Oct 07 '21 at 07:00
  • I am using v16.10.0 – Makashi Oct 07 '21 at 19:24
  • I used your package.json, then typed `npm install` and `node index.js`. Worked fine. –  Oct 07 '21 at 19:26
  • Earlier I was Replit because I had been using my phone but I transferred it over to my VScode and it seemed to work fine, It must have been issue with Replit's IDE – Makashi Oct 07 '21 at 19:33

1 Answers1

0

As mentioned from Chris G, this code works fine.

Code:

fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => response.json())
      .then(data => console.log(data));

Output:

{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Please delete the import line and try again. If it still fails, please check your node version, I successfully tried with 14.17.0.

0kMike
  • 124
  • 1
  • 9