SyntaxError: Cannot use import statement outside of module
SyntaxError: Cannot use import statement outside of module
我查阅了三份文档和其他资源,但仍无法修复我的错误。我刚刚学习 JavaScript,我正在尝试 fetch() 命令,但我无法通过此错误(标题)
这是我的代码
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"
}
}
正如 Chris G 所述,这段代码工作正常。
代码:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data));
输出:
{
"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"
}
请删除导入行,然后重试。如果仍然失败,请检查您的节点版本,我使用 14.17.0 尝试成功。
我查阅了三份文档和其他资源,但仍无法修复我的错误。我刚刚学习 JavaScript,我正在尝试 fetch() 命令,但我无法通过此错误(标题)
这是我的代码
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"
}
}
正如 Chris G 所述,这段代码工作正常。
代码:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data));
输出:
{
"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"
}
请删除导入行,然后重试。如果仍然失败,请检查您的节点版本,我使用 14.17.0 尝试成功。