Having trouble establishing a connection with the OpenWeather API in your Javascript code

I'm trying to show the current weather conditions for the state I enter, but every time I do, it gives an error saying "wrong city name" and then shows as undefined.

const button = document.querySelector('.button');
const inputValue = document.querySelector('.inputValue');
const nam = document.querySelector('.nam');
const desc = document.querySelector('.desc');
const temp = document.querySelector('.temp');

button.addEventListener('click', function() {
    fetch('https://api.openweathermap.org/data/2.5/weather?q=' + inputValue.value + '&appid=0c712e338cabb3996a78ae788fa566a1')
    .then(response => response.json())
    .then(data => {
        const nameValue = data['nam'];
        const temperature = data['main']['temp'];
        const descValue = data['weather'][0]['description'];
        nam.innerHTML = nameValue;
        temp.innerHTML = temperature;
        desc.innerHTML = descValue;
    })
    .catch(err => alert("Oops! Wrong City name!"));
});

Answer №1

If your API call returns an error response [1], make sure to handle exceptions in your code due to its nested structure.

// Since "main" does not exist in the error response, accessing a child of "main" will throw an error.
var temp = data['main']['temp'];

// Similarly, "weather" does not exist in the error response, resulting in an error when trying to access a child of "weather".
var descValue = data['weather'][0]['description'];

It's a good practice to check the response code before parsing the data, as shown below -

.then(response => {
  if (response.cod == 200) {
    // Your logic here
  } else {
    throw new Error(response.message)
  }
).catch(err => alert(err))

In addition, there are a couple of typos in your code -

// The key "nam" does not exist in the response, use "name" instead as shown in the success response [2].
var nameValue = data['nam'];

// You store the description as "descValue"
var descValue = data['weather'][0]['description'];
// However, you are using "description" here
desc.innerHTML = description;

[1] Error response -

{
  "cod": "404",
  "message": "city not found"
}

[2] Success response (if city exists) -

{
  "coord": {...},
  "weather": [...],
  "base": "stations",
  "main": {...},
  "visibility": 10000,
  "wind": {...},
  "clouds": {...},
  "dt": 1618812226,
  "sys": {...},
  "timezone": -14400,
  "id": 4350049,
  "name": "California",
  "cod": 200
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered when entering a value in the Material UI keyboard date picker

When I select a date by clicking on the calendar, it works fine. However, if I initially set the date to empty and then type in the date, it does not recognize the format and displays numbers like 11111111111111111111. This breaks the date format. If I sel ...

Automatically sync textbox width with gridview dimensions

My goal is to dynamically resize a number of textboxes so that they match the width of my gridview's table headers. The gridview will always have the same number of columns, but their widths may vary. However, as shown in the image below, the width va ...

Unable to load a different webpage into a DIV using Javascript

Today has been a bit challenging for me. I've been attempting to use JavaScript to load content into a <div>. Here is the JavaScript code I'm working with: function loadXMLDoc(filename) { var xmlhttp; if (window.XMLHttpRequest) { ...

Terminate the npm build script within a Node.js script

I have developed a node script that checks for the presence of a lock file in my project. If the lock file is not found, I want to stop the npm build process. Any suggestions on how to achieve this? lock-check.js const path = require('path'); c ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

Obtaining the data from the React material-UI Autocomplete box

I have been exploring the React Material-UI documentation (https://material-ui.com/components/autocomplete/) and came across a query. Within the demo code snippet, I noticed the following: <Autocomplete options={top100Films} getOptionL ...

Button click causing TextField to print incorrectly

I am working on implementing a feature in my react application where users can input a search term, and upon pressing the button, it will be used to perform a search. The text input field and button are utilizing material-ui components. At this stage, I si ...

Double-checked in p:commandButton, encountering a race condition with oncomplete

When I execute the server action using p:commandButton, I then refresh the form to display hidden fields and show a dialog. Attempting to refresh only the panels with hidden buttons yields the same result: After I call dialog.show(), a second refresh is t ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

Struggling to retrieve accurate information from database (MSSQL) using PHP and JSON

There seems to be a small hiccup in my project. The query result is blank whenever the first name or last name contains the letter 'ñ'. Here's the code snippet: config.php: <?php ini_set('mssql.charset', 'UTF-8&apos ...

Dealing with Unhandled Promise Rejections in Express.js

I'm providing all the necessary details for this question, however I am confused as to why my callback function is returning an Unhandled Promise Rejection even though I deliberately want to catch the error: (node:3144) UnhandledPromiseRejectionWarni ...

What is the best way to change a date-containing string into a Json object?

I need to convert a string into a JSON Object using JavaScript. However, when I do so, the date in the original string gets completely changed. Here is the string I am working with: var JsonData=[[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01- ...

Attempting to connect JQuery to a different page through a data attribute connection

I am currently working on a slider that connects slides from an external page through data attributes. Here is the setup: Main Page <div id="sitewrapper"> <section class="sliderwrapper"> <div id="slider" data-source="slides-pa ...

Comparing JS Async/Await, Promise, and Callbacks: Which is Best

I'm trying to wrap my head around the differences between callbacks, promises, and async/await. While I understand how callbacks and promises work, I'm struggling with grasping the usage of async/await. I know it's essentially a syntactic su ...

Using JavaScript Imports and Exports in Node.JS

I've been working on a Node.JS REST API using Express and found myself a bit puzzled by the require() and exports statements in Node.JS. Imagine I'm creating a simple application where app.js has the essential app.get statements, routes.js conta ...

Customize the position values of the Ngx-bootstrap Tooltip manually

I have incorporated ngx-bootstrap into my Angular 4 application. The component I am using is ngx-bootstrap Tooltip: After importing it, I am implementing it in my component's view like this: <button type="button" class="btn btn-primary" ...

In mongoose, documents are able to update autonomously without any explicit request

I have encountered an issue with my verification logic. I am sending email links to users for verification, but they are getting verified even before clicking on the link. Below is the code snippet used for user registration: router.post("/register", asyn ...

The ToDate must always be greater than or equal to the FromDate

I have two datepickers, one for the From date and the other for the To date. I want the To date to always be equal to or greater than the From date. I have attempted to solve this issue, but I have not been successful in finding the proper solution. $(d ...

incorporating a qml conditional statement when assigning a class

I have an item and I want to dynamically add a class based on a variable import "class1" import "class2" Item { id: myID property variant myVar: 0; anchors.fill: parent; function update() { switch(myID.myVar) { ...

How to iterate through a Vue data object using forEach loop

I am currently working with a variable in my data: data: function () { return { myVariable: false, } } I'm trying to figure out how to access this variable within a looping function, like the example below: anArray.forEach(functi ...