Home > Net >  SyntaxError: Cannot use import statement outside of module
SyntaxError: Cannot use import statement outside of module

Time:10-08

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"
  }
}

CodePudding user response:

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.

  • Related