JavaScript Node.js Basics Create a Command Line Weather Application Retrieving Data - Solution

Patrik Horváth
Patrik Horváth
11,081 Points

Node.JS API and CITY code is wrong and api key is wrong

hi, i have problem when i type variable in ${ } i getting error because its wrong api.key and its NOT ! when i type it directly to get method it works perfect

const https = require("https");
const api = require("./api.json");

function get(query) {
    const request = https.get('https://api.openweathermap.org/data/2.5/weather?zip=${query}&appid=${api.key}', (response) => {
        let body = "";
        response.on("data", chunk => {
            body += chunk;
        });
        response.on("end", () => {
            console.log(body);
        });
});
}

api.json :

{
  "key" : "385a38ead92aa38a3e4e857ec3323062"
}

2 Answers

Neil McPartlin
Neil McPartlin
14,642 Points

For template literals to work, in the request declaration, you need to replace those single quotes with back ticks.

//Current
const request = https.get('https://api.openweathermap.org/data/2.5/weather?zip=${query}&appid=${api.key}', 

//New
const request = https.get(`https://api.openweathermap.org/data/2.5/weather?zip=${query}&appid=${api.key}`, 
Patrik Horváth
Patrik Horváth
11,081 Points

your "`" is not valid in programing world

you ahve to use ALT + 39 '

Patrik Horváth
Patrik Horváth
11,081 Points

interesting maybe i missed it in ES6 course, Thanks

Sean T. Unwin
Sean T. Unwin
28,648 Points

Is api.json in the same directory as the js file you are calling it from? I ask because the ./ in const api = require("./api.json"); means to use the current directory. Please check that this is not a path issue, meaning the file could not be found.

You could try a console.log(api.key); after declaring the api variable to ensure the api key is accessed correctly.

Patrik Horváth
Patrik Horváth
11,081 Points

Yup it is in same directory also and console log works and i tryed ive API manualy to link and just put ${query} and it telling me this country no exist but if i put it directly to link it works and my Input is Same as Manual input to link =\

Sean T. Unwin
Sean T. Unwin
28,648 Points

What is the value of query if you console.log it? Perhaps this is where the issue lies.

Patrik Horváth
Patrik Horváth
11,081 Points

Interesting log is writed before CODE :

const weather = require("./weather");
const query = process.argv.slice(2).join("_").replace(" ", "_");

weather.get(query);
console.log("LOG:" + query);
C:\Users\Snezn\IdeaProjects\Node.JS\1 - Weather app>node app.js 94040
LOG: 94040
{"cod":"404","message":"city not found"}