JavaScript Tutorials - HTTP Requests




HTTP requests are used to communicate between a client and a server. Example, a web application running in the browser communicates with a weather API running on someone else's server using a GET HTTP request. The response data is then used to populate a widget in the web application.
In JavaScript, the fetch API is used to perform HTTP requests.

A basic example to retrieve data is shown below:


const config = {
  method = 'GET',
  headers: {
      'Content-Type': 'application/json'
    }
}
fetch('http://server.com/url', config)
  .then(response => {
    if (!response.ok) {
      console.log('Error: ' + response.status);
    }
    return response.json();
  })
  .then(data => {
     console.log(data);
   })
  .catch((error) => {
    console.error('Error:', error);
  });


A basic example to send data is shown below:


const config = {
  method = 'POST',
  headers: {
      'Content-Type': 'application/json'
  },
  body: JSON.stringify(somedata)
}
fetch('http://server.com/url', config)
  .then(response => {
    if (!response.ok) {
      console.log('Error: ' + response.status);
    }
    return response.json();
  })
  .then(data => {
     console.log(data);
   })
  .catch((error) => {
    console.error('Error:', error);
  });


Fetch will return successfully unless there is a network error. HTTP error codes do not cause the fetch to reject. HTTP error codes need to be explicitly checked for.

Since fetch communicates with an external server, the call could turn into a long running process. Fetch should be called using promises, as discussed in the previous tutorial post, or from an asynchronous function. Using the fetch API is demonstrated in the implementation below.


Implementation:



For this tutorial implementation, open up the Weather.js file and add the bolded lines below:
NOTE: The example calls the openweathermap API. This API requires a key which can be obtained by creating a free account at https://openweathermap.org/


js/modules/Weather.js:



class Weather {

    // Constructor
    constructor() {
    };

    getLocation() {
        return new Promise((resolve, reject) => {

          const url = "https://ipinfo.io/json";

          fetch(url)
          .then(response => {
            return response.json();
          })
          .then(result => {
            if (result) {
              let location = {
                city: result.city,
                region: result.region,
                loc: result.loc
              };

              resolve(location);
            } else {
              resolve(null);
            }
          });

        });       
    };

    getWeather(coordinates) {
        return new Promise((resolve, reject) => {
          
          const url = 'https://api.openweathermap.org/data/2.5/weather?lat=' + coordinates[0] +
            '&lon=' + coordinates[1] + '&appid=ENTER_YOUR_OPENWEATHERMAP_API_KEY_HERE';
          let config = {
            setRequestHeader: false,
            async: true
          };
          
          fetch(url, config)
          .then(response => {
            return response.json();
          })
          .then(result => {
            if (result) {
              resolve(result);
            } else {
              resolve(null);
            }
          });

        });       
    }  
}

export default Weather;



These lines call the REST API defined in the url variable. A promise is returned to the calling function. When the api call returns the promise resolves and sends back the data received from the REST API.


Next, edit the js/javascript_tutorials.js as follows:



// JavaScript Tutorial

/*
 * This file will add JavaScript
 * to a website.
 */
import TemperatureConverter from "./modules/TemperatureConverter.js";
import Weather from "./modules/Weather.js";

(function() {
  let doc = document;
  let defaultLocation = [-86.7816, 36.1627]; // longitude, latitude

  function setLocation(location) {
    if (location) {
      let locationElement = doc.getElementById("location");
      locationElement.innerHTML = location.city + ", " + location.region;
    }
  }

  function setWeather(data) {
    if (data) {
      let temp = Math.round(data.main.temp);
      try {
        let fahrenheit = TemperatureConverter.convertCelsiusToFahrenheit(
          temp - 273
        );
        console.log("Fahrenheit temperature: " + fahrenheit);
        let temperatureValueElement = document.getElementById(
          "temperatureValue"
        );
        temperatureValueElement.innerHTML = fahrenheit;
        let temperatureUnitsElement = document.getElementById(
          "temperatureUnits"
        );
        temperatureUnitsElement.innerHTML = "F";

        let weather = data.weather[0];
        let main = weather.main;
        let weatherDescriptionElement = document.getElementById(
          "weatherDescription"
        );
        weatherDescriptionElement.innerHTML = main;

        let icon = weather.icon;
        let weatherIconElement = document.getElementById("weatherIcon");
        weatherIconElement.src =
          "https://openweathermap.org/img/w/" + icon + ".png";
      } catch (error) {
        console.log("Error setting weather: " + error.message);
      }
    }
  }

  function init() {
    let weather = new Weather();
    weather.getLocation().then((location, error) => {
      // let coordinates = defaultLocation;
      if (location) {
        setLocation(location);

        let coordinates = location.loc.split(",");
        weather.getWeather(coordinates).then((weatherData, error) => {
          if (weatherData) {
            console.log(typeof weatherData);
            setWeather(weatherData);
          }
        });
      }
    });

  init();
})();


These changes will retrieve the DOM elements that will display the location and weather data. The data received from the REST API calls will then be used to populate the DOM elements for viewing in the browser.


For completeness, the other files in this tutorial example are as follows:

index.html:



<html>
  <head>
    <link rel="stylesheet" href="css/style.css"/>
  </head>

  <body>
    <header>
      <nav>

      </nav>

      <article id="toolbar">
        <article id="currentWeather" class="text-center">
          <section id="location">
          </section>
          <section id="weatherTemperature">
            <span id="temperatureValue"></span>
            <span id="degreeSymbol">°</span>
            <span id="temperatureUnits"></span>
          </section>
          <section id="weatherDescription">
          </section>
          <img id="weatherIcon">                
          </img>
        </article>          
      </article>

    </header>

    <main></main>

    <footer></footer>

    <script src="js/javascript_tutorial.js" type="module"></script>
  </body>
</html>



js/modules/TemperatureConverter.js:



class TemperatureConverter {
  
    static convertKelvinToCelsius(kelvin) {
        if (typeof kelvin !== 'number') {
            throw 'Kelvin value is not a number';
        }
        return Math.round(kelvin - 273);
      }
    
      static convertCelsiusToFahrenheit(celsius) {
        if (typeof celsius !== 'number') {
            throw 'Celsius value is not a number';
        }
        return Math.round((celsius * (9/5)) + 32);
      };
    
      static convertFahrenheitToKelvin(fahrenheit) {
        if (typeof fahrenheit !== 'number') {
            throw 'Fahrenheit value is not a number';
        }
        return Math.round(((5/




export default TemperatureConverter;




css/style.css:




header nav {
  height: 10vh;
  border-bottom: 1px solid darkgray;
}

header #toolbar {
  height: 5vh;
  border-bottom: 1px solid darkgray;
}

main {
  height: 72vh;
  border-bottom: 1px solid darkgray;
}

footer {
  height: 10vh;
  border-bottom: 1px solid darkgray;
}



See a working example at https://www.zofxare.com/zofxare/blog/tutorials/javascript/index.html.

When loading the index.html file in a browser, you should see the city and state of your IP address. You should also see the current temperature and weather info at that location.


Note, the files will need to be loaded onto a web server. If running them locally in Chrome, you may get a CORS error.


The JavaScript tutorial series starts with this post.


(#sponsored)

More JavaScript








Comments