【问题标题】:Weather Data in express and node.js not printing in my command lineexpress 和 node.js 中的天气数据未在我的命令行中打印
【发布时间】:2022-01-11 09:38:56
【问题描述】:
const { response } = require("response");
const express = require("express");
const https = require("https")
const app = express ();

app.get("/", function(req,res) {
  const url = "https://api.openweathermap.org/data/2.5/weather?q=London&applied=536bcef96b2f01cd9b9f076db90807fe&unit=metric";
  https.get(url, function(response) {
    console.log(response.statusCode);
  })

  response.on("data", function(data) {
    const weatherData = JSON.parse(data)
    console.log(weatherData);
  })

  res.send("Welcome to the future");
})

app.listen(3000, function() {
  console.log("listening on port 3000");
})

这里的问题是当我输入 response.on 从 url 获取数据 要在命令行中打印它,它 带来 const { response } = 要求 ("express") 如上图即 对我来说很陌生。 请问,我该如何解决它,这样我才能得到 我的天气数据打印在 CMD 中?

【问题讨论】:

  • 您在第 2 行的 require("express) 处缺少引用 "
  • 这是一个错字。我已经在那里了
  • 您的网址错误。您有一个名为“applied”的查询参数,但它应该是“appid”
  • 你的代码有很多问题。删除const { response } = require("response");,将response.on("data",移到console.log(response.statusCode);之后,const req = https.get(url,然后req.end()...

标签: node.js express https command-line response


【解决方案1】:

你需要改变很多东西。

首先,这一段是错误的:

https.get(url, function(response) {
    console.log(response.statusCode);
})
response.on("data", function(data) {
    const weatherData = JSON.parse(data)
    console.log(weatherData);
})

由于“response”是从“get”函数的回调中接收到的参数,因此需要在函数作用域内声明“response.on”,如下所示:

https.get(url, function(response) {
    console.log(response.statusCode);

    response.on("data", function(data) {
        const weatherData = JSON.parse(data)
        console.log(weatherData);
    })
})

此外,“数据”事件仅传递一大块数据。您还应该监听“结束”事件,并且仅在收到“结束”事件时解析数据

https.get(url, function(response) {
    console.log(response.statusCode);
    const result = []
    response.on("data", function(data) {
        result.push(data);
    })
    .on("end", function() {
        const weatherData = JSON.parse(result.join(""));
        console.log(weatherData);
    })
})

并且由于您没有使用名为“response”的模块,因此您还需要删除它:

const { response } = require("response");

然后更正 cmets 中已经提到的所有错别字,分别是:

  1. 在第 2 行的 require("express) 处添加缺少的引号 "
  2. 删除 console.log("listening on port 3000")` 处的额外支持;第 17 行
  3. 将第 6 行 URL 上的第二个查询参数从“applied”更改为“appid”

【讨论】:

  • 而且,您不能假设一个data 事件包含整个数据。这是否正确取决于数据量和网络状况。累积所有数据,然后在end 事件中全部处理。就个人而言,我不再使用普通的https.get(),因为要编写太多样板代码来安全地使用它并处理错误。我宁愿使用基于 promise 的更高级别的库,例如 got()
  • @jfriend00 你是对的。我编辑了答案以包括“结束”事件侦听器。
【解决方案2】:

首先确认您的网址有效

https://api.openweathermap.org/data/2.5/weather?q=London&appid=536bcef96b2f01cd9b9f076db90807fe&unit=metric

如果您使用的是 Windows 10 或 11,则不需要所有这些响应,只需在 cmd 行尝试此操作(注意您需要将 url 中的每个 &^ 转义像这样^&)

curl -o current.txt https://api.openweathermap.org/data/2.5/weather?q=London^&appid=536bcef96b2f01cd9b9f076db90807fe^&unit=metric

type current.txt

你可以在一行中同时包含两个,但是最后一个 & 不需要 ^escape

curl -o current.txt https://api.openweathermap.org/data/2.5/weather?q=London^&appid=536bcef96b2f01cd9b9f076db90807fe^&unit=metric&type current.txt

下载后,您应该会在控制台中看到响应。

因此您可以以任何您希望的方式(隐藏或不隐藏)调用该命令,或者在屏幕上或您选择的任何应用程序中读取文本文件。

当前.txt

{"coord":{"lon":-0.1257,"lat":51.5085},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":276.78,"feels_like":272.23,"temp_min":275.76,"temp_max":278.14,"pressure":999,"humidity":84},"visibility":10000,"wind":{"speed":6.17,"deg":250},"clouds":{"all":9},"dt":1641696366,"sys":{"type":2,"id":2019646,"country":"GB","sunrise":1641715415,"sunset":1641744666},"timezone":0,"id":2643743,"name":"London","cod":200}

【讨论】:

    【解决方案3】:

    这是一个相当简单的版本,它使用got() 库来发出http 请求。它是一个基于 Promise 的更高级别的库,比 https 库更易于使用,后者在较低级别工作并且需要更多代码才能正常工作和处理错误。

    以下是使用 got() 库的方法:

    const got = require("got");
    const express = require("express");
    const app = express();
    
    app.get("/", async function(req, res) {
        try {
            const url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=536bcef96b2f01cd9b9f076db90807fe&unit=metric";
            const result = await got(url).json();
            console.log(result);
            res.json(result);
        } catch (e) {
            console.log(e);
            res.sendStatus(500);
        }
    });
    
    app.listen(3000, function() {
        console.log("listening on port 3000");
    });
    

    变化:

    1. 固定网址(将 applied 更改为 appid)。
    2. 为 http 请求切换到 got() 库并内置 JSON 解析
    3. 添加错误处理
    4. 以 JSON 格式发送结果

    这会生成以下输出:

    {
      coord: { lon: -0.1257, lat: 51.5085 },
      weather: [ { id: 800, main: 'Clear', description: 'clear sky', icon: '01n' } ],
      base: 'stations',
      main: {
        temp: 276,
        feels_like: 271.47,
        temp_min: 274.33,
        temp_max: 277.49,
        pressure: 1000,
        humidity: 86
      },
      visibility: 10000,
      wind: { speed: 5.66, deg: 250 },
      clouds: { all: 8 },
      dt: 1641707384,
      sys: {
        type: 2,
        id: 2019646,
        country: 'GB',
        sunrise: 1641715415,
        sunset: 1641744666
      },
      timezone: 0,
      id: 2643743,
      name: 'London',
      cod: 200
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 2016-05-01
      • 1970-01-01
      • 2015-05-06
      • 2016-05-12
      相关资源
      最近更新 更多