javascriptnode.jsexpressserverside-javascriptnodejs-server

I always get the wrong response to the FIRST query result (it happens everytime i change my query)


i am doing server side programming using nodejs native. I wrote my code on server.js as given below:

const express = require('express');
const https = require('https');
const bodyParser = require('body-parser');

const app = express();//initialized app as an express app
app.use(bodyParser.urlencoded({extended:true}));
app.use("/public", express.static(__dirname + "/public"));

let newConfirmed = null;
let requestedCountryCode = null;

app.post("/", (req, res) => {
    let selectedCountry = req.body.searchInput;//used body-parser here
    ltBraceIndex = selectedCountry.indexOf('(');
    requestedCountryCode = selectedCountry.slice(ltBraceIndex+1, ltBraceIndex+3)//generating value of the requestedCountryCode variable

    //Get Covid details
    const covidUrl = "https://api.covid19api.com/summary"
    https.get(covidUrl, (response) => {    
        
        let chunks = [];
        response
            .on('data', (chunk)=>{
                chunks.push(chunk);
            })
            .on('end', ()=>{
                let data = Buffer.concat(chunks);
                let covidData = JSON.parse(data); 
                covidData.Countries.forEach(Object => {
                    if(Object.CountryCode === requestedCountryCode){
                        newConfirmed = Object.NewConfirmed;
                    }
                });
            })
            .on("error", (error) => {
                console.error(error);
            });
        
        console.log(newConfirmed);    
    })
});

I have illustrated my issue below in the attached images. (see VS Code terminal)

1.img1: I entered afghanistan in the search bar.

enter image description here

  1. img2: I entered India in the search bar. enter image description here

Why is this happening? Please help me with this issue. I always get the response to the first query result wrong (as shown in the terminal in the images above) everytime i change my query.


Solution

  • The first request gives you null in the log because you declare newConfirmed as such.

    let newConfirmed = null
    

    Now, why it is using the value when you already request from an API?, you might ask.

    It is because you put console.log() outside the end event of the response.

       response
            .on('data', (chunk)=>{
                chunks.push(chunk);
            })
            .on('end', ()=>{
                let data = Buffer.concat(chunks);
                let covidData = JSON.parse(data); 
                covidData.Countries.forEach(Object => {
                    if(Object.CountryCode === requestedCountryCode){
                        newConfirmed = Object.NewConfirmed;
                    }
                });
            })
            .on("error", (error) => {
                console.error(error);
            });
      
        console.log(newConfirmed);
    

    This makes the script execute console.log() before the event end gets fired hence the old value.

    What you need to do to change this is to put the console.log() inside the end event so that it will log when the data is really ready.

       response
            .on('data', (chunk)=>{
                chunks.push(chunk);
            })
            .on('end', ()=>{
                let data = Buffer.concat(chunks);
                let covidData = JSON.parse(data); 
                covidData.Countries.forEach(Object => {
                    if(Object.CountryCode === requestedCountryCode){
                        newConfirmed = Object.NewConfirmed;
                        console.log(newConfirmed);
                    }
                });
            })
            .on("error", (error) => {
                console.error(error);
            });