JavaScript web requests can be made in a number of ways - axios is a library that generally makes them fairly simple.
const axios = require("axios");
axios.get("http://middle-maps.herokuapp.com/api/locations/1008").then(function(response) {
console.log(response.data); // => {"name":"Bag End","lat":"34.15555","lng":"-118.1370833","type":"site","id":1008,"synonyms":[],"images":[],"reviews":[]}
});
We can compare this to a rails web request (with the http
gem, for example):
require 'http'
response = HTTP.get("http://middle-maps.herokuapp.com/api/locations/1008")
p response.parse # => {"name":"Bag End","lat":"34.15555","lng":"-118.1370833","type":"site","id":1008,"synonyms":[],"images":[],"reviews":[]}
In both cases, we start with <library-name>.<request-type>
. In ruby, we can assign the returned value to a variable and just keep writing code. axios, however, requires us to use a callback function (.then()
because JavaScript is asynchronous - that is, each line of code doesn't necessarily wait for the line above it to finish before it starts running. If we try to use follow the same pattern as the http
gem uses, our lines of code below the axios request run before the request is finished:
const axios = require("axios");
var response = axios.get("http://middle-maps.herokuapp.com/api/locations/1008");
console.log(response); // => Promise { <pending> }
console.log(response.data); // => undefined
.then()
, on the other hand, takes as an argument a function to run after the axios request has finished.
Also note that response.data
is how we access the content of the web request (as opposed to response.parse
with the http
gem).