Issue with OpenWeathermap country codes: "city was not located"

I've been working on coding a weather journal app and I'm encountering an issue. When using the fetch method with the URL of openweathermap.com, passing the zip code and country code, it seems to only accept the US as the country code. Despite trying various options, it consistently returns forecast data for the US but displays city not found for any other country. Below is the code snippet:

const generate = document.getElementById('generate').addEventListener('click', function(){
    const zip = document.getElementById('zip').value;
    const countryCode = document.getElementById('countryCode').value;
    endPointData(zip,countryCode,apiKey);
})

const endPointData = async (zip,countryCode,apiKey) => {
    const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?zip=${zip},${countryCode}&appid=${apiKey}`);

    try{
        const data = await res.json();
        console.log(data);
    }
    catch(error){
        // appropriately handles the errors.
        console.log("error",error);
    }
}

const postData = async (url='', data = {}) => {
    const response = await fetch(url,{
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
    });
    try{
        const newData = await response.json();
        return newData;
    }catch(error){
        console.log("error",error);
    }
}

Answer №1

Functioning properly in various regions around the globe.

const apiKey = "yyyyyyyyyyyyyyyyyyyyyyyyyyy";
const zipCode = "220044";
const countryCode = "US";

const fetchDataFromEndpoint = async (zipCode, countryCode, apiKey) => {
    const URL = `https://api.openweathermap.org/data/2.5/weather?zip=${zipCode},${countryCode}&appid=${apiKey}`;

    const response = await fetch(URL);

    try {
        const data = await response.json();
        console.log(data);
    }
    catch(error){
        // handles the errors appropriately.
        console.log("error", error);
    }
}

fetchDataFromEndpoint(zipCode, countryCode, apiKey);

Answer №2

Make sure to log your URL variable and check if the country code is empty. If no country code is specified, the API will default to US.

Test it out first with Postman ()!

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: The document has not been defined - experimenting with vitest

I'm currently working on a Vite project using the React framework. I have written some test cases for my app using Vitest, but when I run the tests, I encounter the following error: FAIL tests/Reservations.test.jsx > Reservations Component > d ...

The closing tag for the "body" element was excluded even though OMITTAG NO was specified

While attempting to validate my contact support page, I encountered the following errors: Omission of end tag for "body", even though OMITTAG NO was specified ✉ You may have forgotten to close an element or intended to self-close an element by ending ...

Setting up SSL (Secure Sockets Layer) on an Express server

I have been attempting to set up SSL in Express using the configuration below, but I keep encountering errors that I am unable to resolve. use strict'; //dependencies var config = require('./config'), //uuid = require('node-uuid& ...

What is the best way to apply a hover rule to a CSS class in order to change the color of a specific row when hovering in

I have managed to successfully apply a classname and add color to a specific row in my react-table. However, I am facing difficulty in adding a hover rule to this className to change the color when I hover over the row. Can someone guide me on how to apply ...

Express.js response.json method can be used to render both HTML and JSON content in the

I have a router that is sending JSON data to the client as shown below: router.get('/', function(req, res, next) { UserModel.selectAllUsers(function(err, vals){ if(err){ console.log(err); } res.json({d: v ...

Manipulating a React table: Customizing a row in the table

Below is the code snippet: const [data, setData] = useState([ {id: 1, name: 'paper', qty: 10}, {id: 2, name: 'bottle', qty: 10}, ]); const [isEditable, setEditable] = useState([]); useEffect(()=>{ data.map(each=>{ ...

Tips for broadcasting the blob

I am currently working on a radio system project that involves streaming live audio from a microphone to the user in real-time. However, I am new to using node.js and unsure of how to achieve this. Can anyone provide guidance on how to stream the audio fro ...

Using HTML5 History API to navigate backwards without allowing the user to move forward (can popState?)

My webpage showcases user information with the help of AJAX for seamless data modification without altering the page layout. The process is straightforward: - Users can view their data when they access their profile. - By clicking the Edit button, a form ...

Using jQuery's addClass() method and then trying to access the width property produces an inaccurate

In my project, I am encountering inconsistent return values for width when adding an "active" class to a selection of 4 items. These items are part of a horizontal slider that needs to adjust its elements' widths as one of them becomes active and chan ...

Caution: Anticipated the server's HTML to include a corresponding <body> within a <div> tag

Upon checking the console, I noticed a warning message appearing. I am puzzled as to why this is happening since I have two matching <body> tags in my index.js file. The complete warning message reads: Warning: Expected server HTML to contain a matc ...

What is the method for categorizing mongoDB documents and displaying _id under a different alias?

db.getCollection("analytics").aggregate( [ { "$match" : { "uID" : { "$in" : [ "202003008", &qu ...

Issues with Javascript causing MongoDB batch insert to fail

I need assistance with optimizing my Javascript code. I have created a script to insert multiple records into a collection at once using "insertMany()". However, the code I wrote is not functioning correctly: var batch = []; for (i=0; i<10; i++) { ...

Issues encountered during transition of HTML document to XML through VBA web scraping when attempting to click on a button

I am currently working on a project that involves using an MSHTML.HTMLDocument code to extract data from a specific webpage. The process involves the following steps: Opening the webpage at "https://www.ksestocks.com/HistoryHighLow" Entering a value ...

Exploring the benefits of using Div and semantic elements in web

After spending more than two months learning HTML, I still find myself uncertain about the most practical coding approach. Despite knowing that it's important not to overthink it, I often wonder if I should stick with simplicity or add extra elements ...

Tips for integrating an angular module that lacks Universal compatibility into an angular/cli application with server-side rendering (SSR) support

Greetings everyone! I've been working on developing an Angular app that utilizes Universal with SSR for quite some time now. At times, while including a module like ngx-editor, I noticed that the server would fail silently without any indication of wh ...

Embracing the potential of async/await by encapsulating promises in

Having some difficulties with async/await and returning a value from a Promise. function testingAsync () { return new Promise((resolve, reject) => { resolve('Greetings!') }) } async function callingAsyncFunction() { await testingA ...

Change the rectangle's position by rotating another rectangle

I am facing a challenge with two rectangles that have pivots attached to them, The task at hand is to align the green rectangle's position based on the rotation of the red rectangle. The desired outcome should resemble the image provided: Despite t ...

I am trying to showcase a collection of images on my homepage, but unfortunately, it is not functioning as expected

Does anyone know how to display images using Angular? I am currently utilizing the pic controller in an AngularJS file. Any assistance would be greatly appreciated. HTML CODE <!DOCTYPE html> <html> <head> <meta charset="utf-8"& ...

Is it true that the react setState function does not function properly with stream data?

I'm currently utilizing PouchDB to synchronize my remote database with my local database. The following code is integrated within the componentDidMount lifecycle method: const that = this var localDB = new PouchDB('localdb') var remoteDB = ...

Why does adding to an array in the Vuex store replace all existing values with the last entry?

Utilizing vuex-typescript, here is an example of a single store module: import { getStoreAccessors } from "vuex-typescript"; import Vue from "vue"; import store from "../../store"; import { ActionContext } from "vuex"; class State { history: Array<o ...