As you probably know very well by now, the internet is made up of a bunch of interconnected computers called servers. When you are surfing the web and navigating between web pages, what you are really doing is telling your browser to request information from any of these servers. It kinda looks as follows: your browser sends a request, waits awkwardly for the server to respond to the request, and (once the server responds) processes the request. All of this communication is made possible because of something known as the HTTP protocol.
@dagoeos The response property may be one of many different data types including, but not limited to a string. Using responseText makes it clear that you’re after the text version of the data, even though it will likely be the same value as response in this case.
That being said, a valid response type is “json” which is our target format for this data, so if we wanted to have that parsing happen automatically, we could set the responseType, skip JSON.parse, and pull directly from xhr.response.
var xhr = new XMLHttpRequest();
xhr.responseType = "json"; // xhr.response will be parsed into a JSON object
xhr.open('GET', "https://ipinfo.io/json", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.response.ip); // no parsing needed
}
}
When I run my HTTP requests getting message in my console that says. XMLHttpRequest cannot load https://medium.com/@aaron.klaser/latest?format=json. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000’ is therefore not allowed access. The response had HTTP status code 401.
This is a really good post. I have a scenario where I want to post a GET request but with a query, much like using the requests package in python. Is it possible to do this by adding some argument to the open()?
#this is downloading the content of a request into a python pandas dataframe object. I have heard of a Javascript package d3, but is there a way to do this by modifying your code above? Thanks.