Search code examples
node.jsexpressserver

Debugging a nodeJS server to respond after crashing


i am working on a simple weather API app using html, nodejs, and express

HTML Code

<p>Enter Any location...</p>
<form action="/" method="post">
     <input type="text" name="cityName" placeholder="location">
     <button type="submit">Submit</button>
</form>

NodeJS

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

const app = express();
app.use(bodyParser.urlencoded({extended:true}));

app.get("/",(req,res)=>{

    res.sendFile(__dirname+"/index.html")
})

app.post("/",(req,res)=>{
    const cityName = req.body.cityName;
    const urls = "https://api.openweathermap.org/data/2.5/weather?q="+cityName+"&appid=18e0286ef90587ff4b9c9d686b23b11c&units=metric";
    https.get(urls,(response)=>{
        response.on("data", (data)=>{
            const weatherObject = JSON.parse(data);
            const weatherTemp = weatherObject.main.temp;
            const weatherIcon= "<img src='https://openweathermap.org/img/wn/"+ weatherObject.weather[0].icon+"@2x.png'</img>";
            res.write("<h1> The Temperature is currently: "+ weatherTemp+". </h1>");
            res.write(weatherIcon);
            res.send();
        })
    });
});

app.listen(3000,()=>{
    console.log("Server is running on port 3000");
});

Once i start my server on my terminal ->nodemon app.js, it works perfectly BUT the moment i type in a incorrect city name or country, my server crashes even if i refresh browser i will be getting "localhost refuse to connect"

How can i get the server to keep running even if invalid Location has been passes into?


Solution

  • you can try to add

    response.on("error",(e) => {
    // error handler
    })
    

    to catch the error and return a proper response with some data to the front