首页 > 解决方案 > why my localhost is loading continously? I have a weather app by fetching the result from APi

问题描述

my code the fetching the api

const fs = require('fs');
var requests = require('requests')
const HomeFile = fs.readFileSync("index.html",'utf-8')

const replacaVal=(tempval,orgVal)=>{
    let temperature = tempval.replace("{%tempvalue%}",orgVal.main.temp);
     temperature = temperature.replace("{%tempminvalue%}",orgVal.main.temp_min);
     temperature = temperature.replace("{%tempmaxvalue%}",orgVal.main.temp_max);
     temperature = temperature.replace("{%location%}",orgVal.name);
     temperature = temperature.replace("{%country%}",orgVal.sys.country);
     return temperature;
    }

const server = http.createServer((req,res)=>{
    if(req.url == "/"){
        requests
        ('http://api.openweathermap.org/data/2.5/weather?q=Pune&appid=d8fa5a4c8994da0555cf7a60a5020ca0')
        .on('data', function (chunk) {
            const objdata = JSON.parse(chunk);
            const arrdata =[objdata]
            //console.log(arrdata[0].main.temp)
            const realTimeData = arrdata.map((val=>replacaVal(HomeFile,val))).join(" ");
            //res.write(realTimeData)
            console.log(realTimeData)
            res.write(realTimeData)
        })
        .on('end', function (err) {
        if (err){ return console.log('connection closed due to errors', err);}
    
        res.end()
    });
    }
});

server.listen(5000,"127.0.0.1")

and the html code where i am putting the data is

    
         <h2 class="location"><i class="fa fa-street-view"></i>{%location%} ,{%country%}</h2>
          <p id="date">MONDAY | SEP 12 | 12:34 PM</p>
          <h1 class="temp">{%tempvalue%}</h1>
          <h3 class="tempmin_max">Min {%tempminvalue%} | Max {%tempmaxvalue%}</h3>
        </div>
      </div>


    </div>

whenever i am starting my local host it is loading continously without showing the error in the console. i have already used the res.end() which should not behave like that. fetching the data is working fine. but the final result is not coming.

标签: node.jsnodejs-server

解决方案


推荐阅读