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.
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.