【问题标题】:How to import fetch to my app.js in NodeJS?如何在 NodeJS 中将 fetch 导入我的 app.js?
【发布时间】:2021-10-01 14:46:52
【问题描述】:

我正在使用 NodeJS 开发一个项目,该项目从 JSON data.json 获取坐标,然后使用该坐标将天气和天气数据写入另一个 JSON。 这里的问题是我的函数使用并等待 fetch,这给了我一个错误,说 fetch is not defined 所以,我做了这里所说的问题,我下载了 fetch,我导入了它,现在它说我需要输入 "type": "module" 在我的package.json 中,所以我做了,现在它说我的var fs=require('fs' 没有定义:c 我正在使用文件系统创建另一个 JSON,欢迎任何帮助,谢谢 c:这是我的 @987654325 @

var fs = require('fs')
import fetch from "node-fetch";

const api_key = '******'

async function calcWeather(){ 
    const info = await fetch('./data.json') // fetch editable c:
    .then(function(response) {
        return response.json();
    });    
    for (var i in info) {
        const lat = info[i][0].latjson;
        const long = info[i][0].lonjson;
        const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
        
        fetch(base)
        .then((responses) => {
        return responses.json();
        })
        .then((data) => {
            var myObject = {  
                Latitud: data.coord.lat,
                Longitud: data.coord.lon,
                Temperatura: data.main.temp, 
                Ciudad: data.name, 
                Humedad: data.main.humidity,
                Descripcion: data.weather[0].description,
            };
            // convert JSON object to a string  
            const _myObject = JSON.stringify(myObject);
            /* console.log(JSON.stringify(myObject)) */
            // write file to disk
            fs.writeFileSync('data2.json', _myObject, 'utf8', (err) => {
                if (err) {
                    console.log(`Error writing file: ${err}`);
                } else {
                    console.log(`File is written successfully!`);
                }
            });
            fs.writeFile('data.txt', _myObject,'utf8', (err) => {
                if (!err){
                    console.log(`Written succesfully! c:`)
                }
            })
        });   
    }   
};
calcWeather()

这是我的 JSON

[
    [
      {
        "latjson": 21.1524,
        "lonjson": -101.7108
      }
    ],
    [
      {
        "latjson": 19.4328, 
        "lonjson":  -99.1346
      }
    ],
    [
      {
        "latjson": 20.6605,
        "lonjson": -103.3525
      }
    ]
  ]

这是我的 package.json c:

  "name": "node-js-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.6",
    "express": "^4.17.1",
    "node-fetch": "^3.0.0"
  }
}

【问题讨论】:

  • 您不能同时使用commonjses6 modules。您可以使用require()import,但不能同时使用。尝试使用import fs from "fs" 并将其设置为module
  • 您的 API 密钥是什么?猜猜你需要使用 require 而不是 import。另外,从 var -> const/let 切换
  • 非常感谢你们!现在它说它无法读取 .json 文件:c at ``` const info = await fetch('./data.json') ```,知道吗? @Ifaruki @DraganS
  • @mrtnjf 是你自己机器上的文件吗?
  • @Ifaruki 是的

标签: javascript node.js json


【解决方案1】:

common.js不能导入ES6模块

您必须将文件重命名为.mjs

您可以创建一个名为insert_whatever_name_you_want.mjs的文件


import fetch from 'node-fetch'

fetch('https://google.com')
    .then(res => res.text())
    .then(text => console.log(text))

使用node app.mjs 运行它

延伸阅读:https://techsparx.com/nodejs/esnext/esmodules-from-commonjs.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 2021-09-24
    • 2023-03-23
    • 2020-12-07
    相关资源
    最近更新 更多