JavaScript: Network (Http) Requests

Amitha Perera
3 min readJan 28, 2020

--

In typical web application architecture we have frontend/client side(detached from the backend) and server side/backend. Normally the backend and frontend run on different servers with different domain names may be in different locations too. They should be able to communicate with each other to share information. Frontend is responsible for capturing the user inputs then validate and send it to the server and also fetch and display the data on browser. Backend is responsible for storing and retrieving data from the database. We should remember that frontend should not directly communicate with database for security reasons.

So the http request and response is the secure way to communicate between client and server. For that http request should includes following details, physical location and the path (url) for the server, http method(GET, PUT, POST, DELETE, PATCH), payload/data. Server can decide which type of data they should accept from the frontend(JSON, Binary, etc..)

How to create a Http request ?

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users')
xhr.onload = () => {
const data = JSON.parse(xhr.response);
}
xhr.send()

XMLHttpRequest is built into the browser and all the browsers support it. After create a new XMLHttpRequest object, can use open method to configure the request. In above case it send a GET request to the given url. Request is made only once the ‘send’ method executed. What about the onload function? what does it do here. Onload function execute once the data of the request received successfully. Then we can parse JSON data to JavaScript data.

xhr.responseType = 'json'

responseType property of the XMLHttpRequest can used to set the data type that we need from server(like above). Then no need to parse json object to the JavaScript.

How to make it promisable ?

I would like to recommend to you following article for learn how to create promises in JavaScript. “JavaScript: Async, Promises & Callbacks

// wrap the above code inside a new promise
const apiRequest = (method, url) => {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json';
xhr.onload = () => {
resolve(xhr.response);
}
xhr.send();
})
return promise;
}
// call the promise method to get users
function getUsers(){
apiReuest('GET', 'https://jsonplaceholder.typicode.com/users')
.then(responseData => {
console.log(responseData);
})
}

To make above XMLHttpRequest call promisify, wrap it inside a new promise. Then we can access the result data inside promise ‘then’ function.

What is fetch() API ?

Fetch api is modern JavaScript alternative for XMLHttpRequest. it also do the same thing, Network Requests. Fetch api also build into the browser but not supported in every browser specially the old browser like IE 7,8. So how to do the api request using fetch api. It is very simple.

fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
return response.json();
});

If we did not pass the http method name as a second parameter it will consider it as a GET request. For the third parameter can set the payload as body. Modern JavaScript world there are number of libraries/packages for Http requests. Axios is one of the those http client for http request. Hope to write something related to those libraries as well.

Until that enjoy the reading :)

--

--