【问题标题】:https api request is not working with https.get(url)https api 请求不适用于 https.get(url)
【发布时间】:2021-02-19 07:37:12
【问题描述】:

我需要从中提取天气 API 数据

https://api.weatherapi.com/v1/current.json?key=f5f45b956fc64a2482370828211902&q=London

当粘贴在网络浏览器和邮递员中时,它会给出响应。但是,一旦合并到 javascript https.get 中,它会因不断加载浏览器并用不需要的信息挂起终端而失败。

app.js:

//jshint esversion:6

const express = require("express");
const https = require("https");

const app = express();


app.get("/",function(req, res){

  const url = "https://api.weatherapi.com/v1/current.json?key=f5f45b956fc64a2482370828211902&q=London";

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

    response.on("data",function(data){
      const weatherData = JSON.parse(data);
      const temp = weatherData.current.temp_c;
      const weatherDescription = weatherData.current.condition.text;
    });
  });

  res.send("Server is up and running");

});


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

【问题讨论】:

    标签: javascript express https


    【解决方案1】:

    我尝试了您使用 https.get() 发布的特定请求,它对我有用。因此,如果没有更多信息,例如关于它究竟是如何失败的,将很难弄清楚确切的问题是什么。您在控制台上看到了哪些消息?您如何访问请求的结果,那么是什么让您认为请求不起作用?

    但除此之外,这不是您通常在 Node.js 中发出请求的方式。如果响应以多个块到达,则“数据”事件可能会被多次发出,因此只有在幸运并且响应以单个块到达时,您的操作方式才会起作用。手动执行此操作的正确方法是侦听所有“数据”事件,连接结果,然后在发出“结束”事件时解析连接的数据。但是,手动执行此操作并不常见。

    执行此操作的更常见方法是使用诸如node-fetch 之类的库来为您发出请求。例如像这样:fetch(url).then((res) => res.json()).then((weatherData) => { const weatherDescription = weatherData.current.condition.text; })

    【讨论】:

    • 一旦我使用 nodeman ( nodeman app.js) 运行它,它就会开始监听端口 3000。但是一旦我在浏览器上运行 localhost:3000/ ,浏览器就会继续加载并且在终端中我运行了 nodeman (hyper) 它显示了一个不特定于原始或预期响应的响应。 [ fetch(url).then((res) => res.json()).then((weatherData) => { const weatherDescription = weatherData.current.condition.text; }) ......... ....to ....fetch(url).then((res) => res.json()).then((weatherData) => { const weatherDescription = weatherData.current.条件.文本;})]
    • 我可以使用 node-fetch 做出正确的响应。感谢那。但是我如何从 api 获取 console.log 的 temp_c 和天气描述?
    • 我不确定您要达到的目标。你想console.log天气信息吗?在这种情况下,只需运行console.log(temp, weatherDescription)。您是否尝试将信息发送到浏览器?在这种情况下,请删除您的 res.send() 调用,而是添加类似 res.send(temp + '\n' + weatherDescription) 的内容。
    • 另外,我不知道nodeman是什么。为什么不使用node app.jsnodejs app.js(取决于您的系统)运行应用程序?
    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2018-06-07
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多