ReactJS | Sending HTTP Requests Using JSX

Prayukti Jain
The Startup
Published in
5 min readJul 20, 2020

--

A single desktop application is beneficial in its own course of action, but if the same application is designed in a way so that it can be deployed over a network, then mostly the latter will be more favorable than the former. Also, an application is often reviewed as more dynamic if the information used, can be altered effortlessly. And in order to make an application dynamic, requesting the server, for the information, is considered as a suitable way out. Hence, we need a good understanding of what requests actually do.

Requests and Responses are basically parts of a transfer protocol. The purpose of transfer protocol is to provide a standard way for clients and servers to talk to each other. The communication is initiated through a request from the client/application side. As soon as the client submits a request to the server, after internalizing the request, the server sends back a response. The response contains status/information about the request.

Now, requests in ReactJS can be submitted in different ways. The one out of which suggests initiating the request through XMLHttpRequest while the other one recommends using Fetch API. Both of these ways are discussed below.

Making HTTP Requests using XMLHttpRequest

Making an HTTP Request does not require the use of any external library. Also, HTTP Request can be a GET or a POST Request. Both of them require creating an instance of XMLHttpRequest, add a readyStateChanged callback, open the request and send it.

Sending an HTTP GET Request :

Below is a react component making a GET Request using XMLHttpRequest:

class MyComponent extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.fetchData();
}
fetchData() {
var myComponent=this;
var xhr=new XMLHttpRequest();
//Set a proper request header. If no header is set, the header with type "*/*"(any type) is sent.
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange=function(){
if(this.readyState==4 && xhr.status==200)
{
// initiated request was submitted successfully and server responded with the resource asked for.
console.log(“Response :”,xhr.responseText);
myComponent.setState({"response":xhr.responseText});
}
};
xhr.open(‘GET’, url);
xhr.send();
}
render() {
return (
<div>
<h1>Response : {this.state.response}!!</h1>
</div>
);}
}

onreadystatechange: It defines a function which is to be called when the readyState property changes.

readyState: It holds the status of XMLHttpRequest.

0: "Request not initialized"
1: "Server connection established"
2: "Request received"
3: "Processing request"
4: "Request finished and response is ready"

status: It holds the HTTP response status codes. A complete list of these codes can be found here. Some most commonly used codes are :

200: "OK"
400: "Bad request"
404: "Page not found"
500: "Internal server error"

Sending an HTTP POST Request:

Initializing a POST request is almost similar to that of the GET request except for two minor alterations. Firstly, this time XMLHttpRequest needs to open a POST request.

xhr.open(‘POST’, url);

Secondly, send method of a POST request can be used to send some data to the server. This parameter of send method is optional but it can be a FormData, JSON, or any other XMLHttpRequestBodyInit.

xhr.send("name=bob&age=20"); 
//xhr.send(document);
//xhr.send();

Making HTTP Requests using Fetch API

The Fetch API is a simple and modern interfacing resource, that makes it easier to make web requests and control responses. It liberates us from writing additional callbacks for redirects. It also facilitates Cross-Origin Resource Sharing (CORS) and uses the promise to deliver a more flexible feature set.

Sending an HTTP GET Request:

Below is react component making a GET request using Fetch API:

class MyComponent extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.fetchData();
}
fetchData() {
var myComponent=this;
fetch(url)
.then(response=>response.json())
.then(
(response)=>{myComponent.setState({"response":response});},
(error)=>{myComponent.setState({"response":error.message});}
);
}
render() {
return (
<div>
{
this.state.error?<h1>Error : {this.state.error}</h1>:
<h1>Response : {this.state.response}!!</h1>
}
</div>
);}
}

The fetch method returns a promise, you can use the then() and catch() method to handle them. This promise rejects when a real failure such as a web browser timeout, a loss of network connection, and a CORS violation occurs. As soon as the request is completed, the requested resource is available. Now, the promise will resolve into a Response object.

The Response object is the API wrapper for the fetched resource.The contents of response can be converted using number of methods like text(), json(), blob(), formData(), arrayBuffer(). These methods again return a Promise that resolves with the complete contents of the fetched resource.

Sending an HTTP POST Request:

Sending a request and processing a response can also be done by using the async/await concept, apart from using the promise and then concept. According to the async/await concept :

The word “async” before a function means a function will always return a promise. Other values are wrapped in a resolved promise automatically. In other words, “async” ensures that the function returns a promise, and wraps non-promises into it.

The word “await” makes JavaScript wait until that promise is settled and returns its result. The async function execution gets paused at the “await” and resumes when the promise is settled. The “await” keyword should be strictly used within an “async” function.

class MyComponent extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.fetchData();
}
async fetchData() {
var myComponent=this;
var response=await fetch(url,{method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name: "Tom"}) });
//response.status gives the response code
//response.statusText gives the message for response status
if(response.status==200){
let data=await response.json();
//process data
myComponent.setState({"response":data});
}
}render() {
return (
<div>
<h1>Response : {this.state.response}!!</h1>
</div>
);}
}

Similarly, a form data can also be submitted through POST requests like :

var formData=new FormData();formData.append(‘name’, ’Tom’);
formData.append(‘age’, ’20');
formData.append(‘file’, file);
var response=await fetch(url, { method: ‘POST’,
headers: { ‘Content-Type’: ‘multipart/form-data’ },
body: formData});
console.log(await response.json());

Conclusion

In this article, we understood the role of request and response, sending the GET and POST requests using XMLHttpRequest and Fetch API, and how Fetch API works with the concepts of promise/then and async/await.

Do look out for other articles to get the knowledge about various topics and feel free to drop a comment for doubts or suggestions.

What are the top 10 useful functions of Underscore.js?

What are Decorators in Python?

Multithreading in Java

Understanding Apache Derby using Java

TCP/IP Socket Programming in Java

How to send HTTP Requests using React JSX?

--

--

Prayukti Jain
The Startup

Software Engineer at Walmart Global Tech | Content Writer | Open to Learn and Help