Hi I’m creating a simple web app to fetch city data from geonames api with the url : http://api.geonames.org/searchJSON
But when I get the data back its an empty array. I have tried the api in postman and directly in the browser and get the correct result. But not from the app. Right now I’m just console.logging the data so you might have to check the console for this. The app is made by using node and express server.
my server.js:
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path')
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors())
// Initialize the main project folder
app.use(express.static(path.join('application')));
app.get("/all", function sendData(req, res) {
res.send(projectData);
})
app.post("/add", (req, res) => {
projectData['temp'] = req.body.temp;
projectData['date'] = req.body.date;
projectData['content'] = req.body.content;
res.send(projectData);
})
// Setup Server
app.listen(8080, () => {
console.log("listening on port 3000")
console.log("Go to http://localhost:8080")
})
my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form id="userInfo">
<label for="city">Enter city</label>
<input type="text" name="city" id="city">
<button type="submit" id="submitBtn">Submit</button>
</form>
</div>
</body>
<script src="app.js"></script>
</html>
my app.js:
const username = "demo";
const baseURL = "http://api.geonames.org/searchJSON"
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
e.preventDefault();
const city = document.getElementById("city");
if (city !== "") {
getCoords(username, city, baseURL)
.catch(function (error) {
console.log(error);
alert("Invalid zipcode");
})
}
})
const getCoords = async (username, city, baseURL) => {
// res equals to the result of fetch function
const res = await fetch(`${baseURL}?q=${city}&username=${username}`);
try {
// data equals to the result of fetch function
const data = await res.json();
console.log(data);
return data;
}
catch (error) {
console.log("error", error);
}
};
>Solution :
The problem is that you are passing the city element object as the value to the query instead of the actual value property of the element.
You should replace this line:
const city = document.getElementById("city");
With this one:
const city = document.getElementById("city").value;
While passing the element object to the query, as per the JS rules of conversion, it will be converted into the string ‘[object HTMLInputElement]’:
http://api.geonames.org/searchJSON?q=[object%20HTMLInputElement]&username=demo
Tip: make it a habit to console.log the actual value that you are passing to a function call in order to make sure that you are passing the correct value. For example, instead of:
const res = await fetch(`${baseURL}?q=${city}&username=${username}`);
Double check the value that you are passing to fetch via a simple console.log:
const URL = `${baseURL}?q=${city}&username=${username}`;
console.log("URL:", URL); // <= Am I seeing the correct value?
const res = await fetch(URL);