简体   繁体   中英

SyntaxError: Cannot use import statement outside of module

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM