节点获取问题 Javascript

Trouble with node-fetch Javascript

所以我正在尝试使用来自天气 API 的数据构建一个天气应用程序。

import fetch from 'node-fetch'

//fetch weather API
let weather
let getWeather = async() => {
let url = \https://api.openweathermap.org/data/2.5/weather?q=auckland&appid=c156947e2c7f0ccb0e2a20fde1d2c577`try {let res = await fetch(url)weather = await res.json()    } catch (error) {console.log("error")    } let weatherMain = weather.weather.map( el => el.description)if(weatherMain ="Rain"){console.log(weatherMain)// weatherImg = "[https://icon-library.com/images/raining-icon/raining-icon-1.jpg](https://icon-library.com/images/raining-icon/raining-icon-1.jpg)"    }  }console.log(getWeather())`

我的问题是当 运行 in vscode 时出现此错误:

SyntaxError: Cannot use import statement outside a module

在浏览器中 运行 时出现此错误:

Uncaught TypeError: Failed to resolve module specifier "node-fetch". Relative references must start with either "/", "./", or "../".`

不确定到底发生了什么,有人可以解释一下发生了什么吗?

我之前试过一次 fetch API,那次我不需要导入 fetch,所以我很困惑。

SS

编辑 - 现在明白了,运行 在浏览器中和在 vscode 中是两个不同的东西。在浏览器中有效的不一定在 Node.js 中有效 当运行在浏览器中时,不需要导入fetch。

谢谢大家

let weather;
let getWeather = async () => {
  let url = `https://api.openweathermap.org/data/2.5/weather?q=auckland&appid=c156947e2c7f0ccb0e2a20fde1d2c577`;
  try {
    let res = await fetch(url);
    weather = await res.json();
    console.log('weather', weather);
  } catch (error) {
    console.log(error);
  }
  let weatherMain = weather.weather.map((el) => el.description);
  if ((weatherMain = 'Rain')) {
    console.log('weatherMain', weatherMain);
    let weatherImg =
      '[https://icon-library.com/images/raining-icon/raining-icon-1.jpg](https://icon-library.com/images/raining-icon/raining-icon-1.jpg)';
    return weatherImg;
  }
};

const main = async () => {
  const data = await getWeather();
  console.log('data', data);
};

main();

是的,如果您在浏览器中 运行ning js,则无需导入 fetch 是对的。但是我看到你在导入node-fetch,这个包是用来给node系统带来fetch(window.fetch)的

但是如果你想在节点中运行它,那么你应该知道节点不支持ES6模块。但是您可以将实验标志用于 运行 代码。例如 node --experimental-modules app.mjs