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

Nikola Jankovic
Nikola Jankovic
10,793 Points

console.dir(core); trows an error

const http= require("http");
const query="london";
const api= require('./api.json');

function printMessage(city, temperature , airPresure) {
  const string= `In ${city} temperature is ${temperature} and air resure is ${airPresure}`;
  console.log(string);
};

function get(query) {
  const request= http.get(`http://api.openweathermap.org/data/2.5/forecast?q=${query}&APPID=${api.key}`, response=> {
    let body= "";
    response.on("data", data=>{
      body+= data.toString;
    });
    response.on('end', ()=>{
      const core= JSON.parse(body);
      console.dir(core);
    });
  });
};

get(query);

This is the error message in the console=> Unexpected token u in JSON at position 1

1 Answer

Jordan Watson
Jordan Watson
14,738 Points

Within the function get() you have a variable

 let body = ""

This is within a function call this is now scoped within that please see comments!

function get(query) {
  let body= ""; // Move this to the top of the function! 
  const request= http.get(`http://api.openweathermap.org/data/2.5/forecast?q=${query}&APPID=${api.key}`, response=> {
    // let body= ""; <--- This is scoped within this function ^
    response.on("data", data=>{
      body+= data.toString;
    });
    response.on('end', ()=>{
      const core= JSON.parse(body);
      console.dir(core);
    });
  });
};