Javascript https api请求无法使用https.get(url)
我需要从中提取天气API数据 它会在粘贴到web浏览器和postman中时给出响应。但是,一旦合并到javascripthttps.get中,它就会失败,因为它会不断加载浏览器,并用不需要的信息挂起终端 app.js:Javascript https api请求无法使用https.get(url),javascript,express,https,Javascript,Express,Https,我需要从中提取天气API数据 它会在粘贴到web浏览器和postman中时给出响应。但是,一旦合并到javascripthttps.get中,它就会失败,因为它会不断加载浏览器,并用不需要的信息挂起终端 app.js: //jshint esversion:6 const express = require("express"); const https = require("https"); const app = express(); app
//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");
});
我尝试了您使用https.get()发布的特定请求,它对我有效。因此,如果没有更多的信息,例如关于它到底是如何失败的信息,就很难找出确切的问题是什么。您在控制台上看到了什么消息?您如何访问请求的结果,那么是什么让您认为请求不起作用 但除此之外,这并不是通常在节点中发出请求的方式。如果响应以多个块的形式到达,“数据”事件可能会多次发出,因此,只有在幸运且响应以单个块的形式到达时,您这样做的方式才会起作用。手动执行此操作的正确方法是侦听所有“数据”事件,连接结果,然后在发出“结束”事件时,解析连接的数据。然而,这是相当罕见的手工操作
一种更常见的方法是使用库(如)为您提出请求。例如:
fetch(url)。然后((res)=>res.json())。然后((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.condition.text;})我可以使用节点fetch做出正确的响应。谢谢你。但是,我如何从api中获取console.log的温度和天气描述?我不确定您想要实现什么。您正在尝试控制台。记录天气信息吗?在这种情况下,只需运行console.log(temp,weatherDescription)
。您正在尝试将信息发送到浏览器吗?在这种情况下,请删除您的res.send()
调用,并添加类似res.send(temp+'\n'+weatherDescription)
的内容。此外,我不知道nodeman是什么。为什么不使用node app.js
或nodejs app.js
运行应用程序(取决于您的系统)?