2

I have very little experience working with Node.js and jQuery and have been searching for the last few hours for a solution. I have an API from openweathermap.com () that returns weather information in the JSON format, and I am trying to pull the temperature value.

I am using Node.js to run a program that can be accessed from any device on the network and I have previously used jQuery on the client to read the file using $.getJSON but am in the process transferring most of my code to the server side to prevent needing a browser open at all times in order for the program to run properly. Obviously you can't use jQuery with node.js but i tried server adaptations for node.js including cheerio, jsdom, and a standard jquery add-on but none of them would do the trick. I can't use XMLHttpRequest or http.get because its being run server side and I can't simply use JSON.parse because it is pulling from a website.

How can I pull the data from the website, store it as an object, and then pull data from it while using just pure javascript?

Here is what I originally had running on the client:

	var updateWeather = function(){
	
		$.getJSON('http://api.openweathermap.org/data/2.5/weather?id=5802340&units=imperial&appid=80e9f3ae5074805d4788ec25275ff8a0&units=imperial', function(data) {
			
			socket.emit("outsideTemp",data.main.temp);	

		});
	
	}
	
	updateWeather();
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>

1
  • A quick note... it looks like the "appid" URL parameter is your API key? You might want to edit this out of your question, or switch to a different API key, as somebody might grab this one now that it is public. Commented Jun 19, 2019 at 6:35

2 Answers 2

3

NodeJS natively supports JSON -- so no "special" work needed. I would recommend using an http client that makes our life easier, like axios, but you can do this natively. I have provided two snippets below for you to get started:

Using popular HTTP Client

 const axios = require('axios');

axios.get('http://api.openweathermap.org/data/2.5/weather?id=5802340&units=imperial&appid=80e9f3ae5074805d4788ec25275ff8a0&units=imperial').then((res) => {
    console.log(res.data)
})

Plain NodeJS (taken from the NodeJS Docs)

const http = require('http');

http.get('http://api.openweathermap.org/data/2.5/weather?id=5802340&units=imperial&appid=80e9f3ae5074805d4788ec25275ff8a0&units=imperial', (res) => {
  const { statusCode } = res;
  const contentType = res.headers['content-type'];

  let error;
  if (statusCode !== 200) {
    error = new Error('Request Failed.\n' +
                      `Status Code: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error('Invalid content-type.\n' +
                      `Expected application/json but received ${contentType}`);
  }
  if (error) {
    console.error(error.message);
    // Consume response data to free up memory
    res.resume();
    return;
  }

  res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => { rawData += chunk; });
  res.on('end', () => {
    try {
      const parsedData = JSON.parse(rawData);
      console.log(parsedData);
    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(`Got error: ${e.message}`);
});
Sign up to request clarification or add additional context in comments.

1 Comment

A quick note: if you decide to use axios, you will need to install the axios dependency via npm. You can find installation instructions on their github page
0

Many people use request / request promise with node

const req = require('request-promise');

req.get({
    uri: 'http://api.openweathermap.org/data/2.5/weather?id=5802340&units=imperial&appid=80e9f3ae5074805d4788ec25275ff8a0&units=imperial',
    json: true
}).then(e => {console.log(e.coord)});

4 Comments

Note that request is now deprecated.
Is it? @jonrsharpe I can't find any notice on github. What's the replacement?
Thanks! So if I used this and then instead of console.log(e) i used something like var ex = JSON.parse(e); and then console.log(ex.main.temp); would that work?
Omit the JSON.parse @BradyUnderwood, json:true already handles this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.