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 trial

JavaScript

api request + api key

Hello !

Let's say a have the API key n : 111111 in a folder call api.json. then on weather.js I do the request like this :

function get(query) { const request = https.get(api.openweathermap.org/data/2.5/weather?q=${query}&appid=${api}, response => { let body = ""; // Read the data response.on('data', chunk => { body += chunk; }); response.on('end', () => { console.log(body); //Parse data //Print the data }); }); } Im really not getting this subject ! can someone please recomend extra material to read ? or explain to me how to write the https.get request properly ?

Thank you !!

1 Answer

Hi Catalina, thanks for this question. I can see that you are or wanting to use Node's https module to make the API request.

I tried to reformat the get() function that you had to make it easier for me to read. you can do that next time with 6 backticks surrounding your code with three backticks on top and three backticks at the bottom.

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

There are several ways you can make an api request, but here is a good resource if you are just getting started: https://teamtreehouse.com/library/introducing-the-project-17

or If you just want to use Node you can follow this format bellow. follow this link for more details - https://nodejs.org/api/https.html#https_https_get_options_callback

const https = require('https');

https.get('https://encrypted.google.com/', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});

Hopefully, some of these suggestions were helpful.