skip to Main Content
const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
    res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res){
    const query = req.body.cityname;
    const apikey = "be542b6232b2bc2d159d89e25bf419fc";
    const unit = "metric";
    const url = "https://api.openweathermap.org/data/2.5/weather?q= " + query + "&appid= " + apikey + "&units= " + unit;
    https.get(url, function(response){
        console.log(response.statusCode);
        response.on("data", function(data){
            const weatherData = JSON.parse(data);
            const temp = weatherData.main.temp;
            const weatherDescription = weatherData.weather[0].description;
            const icon = weatherData.weather[0].icon;
            const imageURL = "https://openweathermap.org/img/wn/" + icon + "@2x.png";
            res.write("<p>The weather is currently " + weatherDescription + " </p>");
            res.write("<h1>The temperature in " + query + " is " + temp + " degree celsius.</h1>");
            res.write("<img src = " + imageURL + ">");
            res.send();
        });
    });
});
app.listen(1500, function(){
    console.log("Server is running on port 1500");
});

2

Answers


  1. The issue with the 401 error could be related to how you are forming the URL for the OpenWeatherMap API. Make sure there are no extra spaces in the URL, and the API key is appended correctly. Also, ensure that the city name is correctly received from the request.

    Here is a modified version of your code:

    const express = require("express");
    const https = require("https");
    const bodyParser = require("body-parser");
    
    const app = express();
    
    app.use(bodyParser.urlencoded({ extended: true }));
    
    app.get("/", function (req, res) {
      res.sendFile(__dirname + "/index.html");
    });
    
    app.post("/", function (req, res) {
      const query = req.body.cityname;
      const apikey = "be542b6232b2bc2d159d89e25bf419fc";
      const unit = "metric";
    
      // Ensure there are no extra spaces in the URL
      const url =
        "https://api.openweathermap.org/data/2.5/weather?q=" +
        query +
        "&appid=" +
        apikey +
        "&units=" +
        unit;
    
      https.get(url, function (response) {
        console.log(response.statusCode);
    
        let data = "";
    
        response.on("data", function (chunk) {
          data += chunk;
        });
    
        response.on("end", function () {
          try {
            const weatherData = JSON.parse(data);
    
            if (weatherData.cod === "404") {
              // Handle case when city is not found
              res.send("<h1>City not found. Please try again.</h1>");
              return;
            }
    
            const temp = weatherData.main.temp;
            const weatherDescription = weatherData.weather[0].description;
            const icon = weatherData.weather[0].icon;
            const imageURL =
              "https://openweathermap.org/img/wn/" + icon + "@2x.png";
    
            res.write("<p>The weather is currently " + weatherDescription + " </p>");
            res.write(
              "<h1>The temperature in " + query + " is " + temp + " degree celsius.</h1>"
            );
            res.write("<img src=" + imageURL + ">");
            res.send();
          } catch (error) {
            // Handle JSON parsing error
            console.error("Error parsing JSON:", error);
            res.send("<h1>Internal Server Error</h1>");
          }
        });
      });
    });
    
    app.listen(1500, function () {
      console.log("Server is running on port 1500");
    });
    

    Changes made:

    1. Used the response.on("end", ...) event to wait for the complete response data.
    2. Checked for a 404 response from the OpenWeatherMap API to handle cases where the city is not found.
    3. Removed extra spaces in the URL concatenation.
    4. Added error handling for JSON parsing errors.

    Please try this modified code and see if it resolves the issue. If the problem persists, you may want to check the OpenWeatherMap API documentation and verify the correct usage of the API key and parameters.

    Login or Signup to reply.
  2. Since you mention that you’ve ‘have copied the whole code from angela yu’s course’, it’s likely that the API key being used is no longer valid, hence you’re getting a response with 401 status.

    See this for more details: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401

    To fix this, you would have to generate new API key for api.openweathermap.org/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search