简体   繁体   English

express 和 node.js 中的天气数据未在我的命令行中打印

[英]Weather Data in express and node.js not printing in my command line

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")`;
})

The problem here is that when I type response.on to get data from the url to print it in the command line, it brings const { response } = require ("express") as shown above which is very alien to me.这里的问题是,当我键入 response.on 以从 url 获取数据以在命令行中打印时,它会带来如上所示的const { response } = require ("express") ,这对我来说非常陌生。 Please, how do I fix it so I can get my weatherData printed in the CMD?请问,我该如何修复它,以便我可以在 CMD 中打印我的 weatherData?

There are quite a few things you'll need to change.有很多事情你需要改变。

First, this section is wrong:首先,这部分是错误的:

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

Since "response" is a parameter you receive from the callback on the "get" function, you need to declare the "response.on" inside the funcion scope, like this:由于“response”是您从“get”function 的回调中收到的参数,因此您需要在函数 scope 中声明“response.on”,如下所示:

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

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

Also, the "data" event only delivers a chunk of data.此外,“数据”事件仅传递一大块数据。 You should be listening for an "end" event aswell, and only parse the data when you receive the "end" event您还应该监听“结束”事件,并且仅在收到“结束”事件时解析数据

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);
    })
})

And since you're not using the module named "response", you also need to remove this:而且由于您没有使用名为“response”的模块,因此您还需要删除它:

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

And then correct all the typos that were already mentioned in the comments, which were:然后更正评论中已经提到的所有错别字,它们是:

  1. Add the missing quote " at require("express) on line 2在第 2 行的 require("express) 处添加缺少的引号 "
  2. Remove the extra backsting at console.log("listening on port 3000")`;删除 console.log("listening on port 3000")` 处的额外支持; on line 17在第 17 行
  3. Change the second query parameter on your URL on line 6 from "applied" to "appid"将第 6 行 URL 上的第二个查询参数从“applied”更改为“appid”

First confirm your url is valid首先确认您的 url 有效

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

If you are using windows 10 or 11 you don't need all those responses simply try this at cmd line ( NOTE you need for each & within the url to escape with ^ like this ^& )如果您使用的是 windows 10 或 11,则不需要所有这些响应,只需在 cmd 行尝试此操作(注意,您需要 Z572D4E4E421E5E6B9BC11D815E8A02711 中的每个&来转义^ ^&

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

type current.txt

you could include both in one line but for the &type that last & does not need ^escape您可以将两者都包含在一行中,但对于最后一个 & 不需要 ^escape 的 &type

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

after the download you should see the response in the console.下载后,您应该会在控制台中看到响应。

so you can call that command any way you wish (hidden or not) and or read the text file on the screen or in any application you choose.因此您可以以任何方式调用该命令(隐藏或不隐藏),或者在屏幕上或您选择的任何应用程序中读取文本文件。

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}

Here's a fairly simple version using the got() library for making the http request.这是一个相当简单的版本,使用got()库发出 http 请求。 It's a promise-based, higher level library that is just a lot easier to use than the https library which works at a lower level and requires more code to work properly and handle errors.它是一个基于 Promise 的更高级别的库,它比https库更易于使用,后者在较低级别工作并且需要更多代码才能正常工作和处理错误。

Here's how you would do this with the got() library:以下是使用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");
});

Changes:变化:

  1. Fixed URL (change applied to appid ).修复了 URL(更改applied appid )。
  2. Switch to got() library for the http request and built in JSON parsing切换到got()库以获取 http 请求并内置 JSON 解析
  3. Add error handling添加错误处理
  4. Send result as JSON发送结果为 JSON

This generates the following output:这将生成以下 output:

{
  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
}

You need to close the string for express in const express = require("express);您需要在const express = require("express);中关闭express的字符串。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM