https api request is not working with https.get(url)

I need to pull the weather API data from

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

It gives a response when pasted in the web browser as well as in postman. But, once incorporated in javascript https.get it fails by continuously loading the browsers and hanging the terminal with unwanted informations.

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

1 thought on “https api request is not working with https.get(url)”

  1. I tried the specific request that you posted using https.get() and it worked for me. So it will be difficult to figure out what is the exact problem without more information, for example about how exactly it is failing for you. What messages are you seeing on the console? How are you accessing the result of the request, so what makes you think that the request didn’t work?

    But apart from that, that is not how you usually make requests in Node. The "data" event may be emitted multiple times if the response arrives in multiple chunks, so the way you do it will only work if you are lucky and the response arrives in a single chunk. The proper way to do this by hand would be to listen to all "data" events, concatenate the result, and then when the "end" event is emitted, parse the concatenated data. However, it is rather uncommon to do this by hand.

    A more common way to do this would be to use a library such as node-fetch to make the request for you. For example like this: fetch(url).then((res) => res.json()).then((weatherData) => { const weatherDescription = weatherData.current.condition.text; }).

    Reply

Leave a Comment