Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBrian Patterson
19,588 PointsGetting an error from his code
I have gone through his code and I am getting the following error.
undefined:2
<!DOCTYPE html>
^
SyntaxError: Unexpected token < in JSON at position 1
at Object.parse (native)
at IncomingMessage.response.on (/Users/briankaty1/Dropbox/JavaScript/consoleWeatherApp/weather.js:24:32)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
This is the code I have for teh weather.js file.
const https = require('https');
const api = require('./api.json');
//const city = "London";
function printWeather(weather) {
const message = `Current temperature in ${weather.location.city} is
${weather.current_observation.temp_f}f`;
console.log(message);
}
//connecting to openweather API.
//http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&appid=8a99df7bf7ef4a4a202732c392b2d240"
function get(query) {
const request = https.get(`https://api.wunderground.com/${api.key}/geolookup/conditions/q/CA/${query}.json`, response => {
let body = "";
response.on('data', chunk => {
body += chunk;
});
response.on('end', () => {
//parse the data
const weatherData = JSON.parse(body);
printWeather(weather);
});
//print the data.
});
}
module.exports.get = get;
and this is the code I have for app.js file.
const weather = require('./weather');
const query = process.argv.slice(2).join("_").replace(' ', '_');
weather.get(query);
Not sure what I have done wrong.
1 Answer
Steven Parker
231,269 PointsI see two issues: first, the request URL is not properly constructed here:
`https://api.wunderground.com/${api.key}/geolookup/conditions/q/CA/${query}.json`
It's missing the term "/api/" right before the key, and unless you only want to look up cities in California, it should not have the term "/CA/" between the "q" and the query. A correct and more typical URL construction would be:
`https://api.wunderground.com/api/${api.key}/geolookup/conditions/q/${query}.json`
Then when the data is parsed it is assigned to the constant "weatherData", but when the "printWeather" function is called on the next line, it is given the argument "weather" (which is undefined).