简体   繁体   English

如何在 NodeJS 中将 fetch 导入我的 app.js?

[英]How to import fetch to my app.js in NodeJS?

I'm working on a project in NodeJS that takes coords from a JSON data.json and then uses that coords to bring the weather, and then that data of the weather, to write it into another JSON. The issue here is that my function uses and wait fetch, and that gives me an error that says fetch is not defined so, I did what a question here said, I downloaded fetch, I imported it and now its says that I need to type "type": "module" in my package.json , so I did and now it says that my var fs=require('fs' is not defined:c I'm using filesystem to create that another JSON, any help is welcomed, thank you c: here's my app.js我正在 NodeJS 中进行一个项目,该项目从 JSON data.json中获取坐标,然后使用该坐标带来天气,然后将天气数据写入另一个 JSON。这里的问题是我的 function使用并等待提取,这给了我一个错误,说提取没有定义所以,我做了这里所说的问题,我下载了提取,我导入了它,现在它说我需要输入"type": "module"在我的package.json中,所以我做了,现在它说我的var fs=require('fs'未定义:c 我正在使用文件系统创建另一个 JSON,欢迎任何帮助,谢谢 c:这是我的app.js

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()

and here's my JSON这是我的 JSON

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

and here's my package.json c:这是我的 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"
  }
}

You can't import ES6 module in common.js你不能在common.js中导入 ES6 模块

You have to rename your file to have a .mjs您必须重命名文件才能拥有.mjs

You can create a file called insert_whatever_name_you_want.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))

Run it with node app.mjs使用node app.mjs运行它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将反应组件导入我的app.js - Unable to import react component to my app.js 如何使用react_intl将语言文件数据动态导入到我的APP.js中 - how to dynamically import languages files data into my APP.js using react_intl 如何使用Angular app.js文件运行NodeJS API? - How to run NodeJS API with Angular app.js file? 如何在Nodejs中传递数据“控制器”而不是“app.js” - How to pass data "controller" instead of "app.js" in Nodejs 如何在 App.js 中导入 TomSelect 以避免浏览器错误? - How to import TomSelect in App.js to avoid browser error? Nodejs 如何添加另一个主 app.js 并使用它们来使我的代码干净? - Nodejs how can I add another main app.js and use both of them to make my code clean? 如何在 app.js 文件中呈现我的主组件? - How to render my home component in the app.js file? 如何在 React 中将我的“./Projects”文件链接到 app.js? - How do link my './Projects' file to app.js in React? 我的提取给了我意外的令牌 < in JSON at position 0 Promise.then (async) (anonymous) @App.js:5 invokePassiveEffectCreate - my fetch gives me Unexpected token < in JSON at position 0 Promise.then (async) (anonymous) @ App.js:5 invokePassiveEffectCreate 无法将我的商店文件导入App.js错误:“商店”应列在项目的依赖项中 - Cannot import my store file into App.js error: 'store' should be listed in the project's dependencies
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM