0

Why is it when I save my API key, location, etc. in a constant the app crashes? If I comment the first const url and I leave the params inside the url works just fine.

app.get('/', function(req, res) {
    const query = "London";
    const apiKey = "c3fd0e578a1e8ead729deb6f25";
    const unit = "metric";

    const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;

    const url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=c3fd0e578a1e8ead729deb6f25d&units=metric"
    
    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 iconURL = "http://openweathermap.org/img/wn/" + icon + "@2x.png";
            
            res.set("Content-Type", "text/html");
            res.write("<h1>The temperature in London is " + temp + "C</h1>");
            res.write("<p>The weather is currencly " + weatherDescription + "</p>");
            res.write("<img src=" + iconURL + ">");
            res.send();
        });

Here is what I get in the Terminal. It points me to the const temp but there is nothing wrong with it, if I comment it out, then it points me to the next one.

/Users/Desktop/code/Web Dev. Bootcamp/WeatherProject/app.js:22
            const temp = weatherData.main.temp;
                                          ^

TypeError: Cannot read properties of undefined (reading 'temp')
    at IncomingMessage.<anonymous> (/Users/Desktop/code/Web Dev. Bootcamp/WeatherProject/app.js:22:43)
    at IncomingMessage.emit (node:events:513:28)
    at Readable.read (node:internal/streams/readable:539:10)
    at flow (node:internal/streams/readable:1023:34)
    at resume_ (node:internal/streams/readable:1004:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...
Eduard
  • 53
  • 6
  • 2
    "There is nothing wrong with it" - there is something wrong with it, just as the error explains, you are accessing the property `temp` of a value that's `undefined`, i.e. `weatherData.main` is `undefined`. You should look at what `weatherData` actually contains. – CherryDT Jan 15 '23 at 12:54
  • 1
    Requesting the URL you've posted results in a HTTP 401 error, `Invalid API key`, and this is why the resulting object has no `main` or `temp` properties. That said, you should probably revoke the API key you've just made public and get a new one. – Gereon Jan 15 '23 at 12:55
  • 2
    You can’t have `const url` twice in the same scope. Instead of concatenating query parameters manually, please use the [`URL` API](//developer.mozilla.org/en/docs/Web/API/URL) and its `searchParams` property, which [_correctly encodes_ parameters](/a/44160941/4642212): `const url = new URL("https://api.openweathermap.org/data/2.5/weather"); url.searchParams.set("q", query); url.searchParams.set("appid", apiKey); url.searchParams.set("units", unit);`. – Sebastian Simon Jan 15 '23 at 12:55
  • What is unclear about an error message such as _“Cannot read property `temp` of `undefined`”_? You can’t read properties of `undefined`, but that’s what happens at `weatherData.main.temp` because `weatherData.main` is `undefined`; it’s trying to get `temp` off of `undefined` — not possible. If you don’t know why `weatherData.main` is `undefined`, use the debugger or look at intermediate values: `console.log(weatherData);`. In Firefox, you can click the “[\[Learn more\]](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Errors/Unexpected_type)” link next to the error message. – Sebastian Simon Jan 15 '23 at 12:57
  • That's not the correct api key. I've changed it on purpose. I know I cannot have two url, that's just to show you that the second url works just fine when the first is commented out but not vice-versa. – Eduard Jan 15 '23 at 12:57
  • @Eduard So does it work if you use the `URL` API and correctly encode the parameters? – Sebastian Simon Jan 15 '23 at 12:59
  • Yes, if I use the second url the whole script works just fine. The problem is when I put the api key, location, etc in constants and I concatenate them into the url. – Eduard Jan 15 '23 at 13:01
  • @Eduard That wasn’t my question. Read my first comment again and try using the `URL` API. You aren’t using it in the code you’ve shown, yet. – Sebastian Simon Jan 15 '23 at 13:06
  • @SebastianSimon thank you! It worked, you were right. Much more complicated than I was expecting it. – Eduard Jan 15 '23 at 13:20

0 Answers0