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");
});
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
2
Answers
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:
Changes made:
response.on("end", ...)
event to wait for the complete response data.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.
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/