How to send HTTP requests in React

How to send HTTP requests in React

ยท

4 min read

In the tutorial, you will understand how to reach out to the web or connect your front-end with the backend in React, using a library called Axios.

Let's see.

Typically, when you send a request to the server from a React app, what it returns to you is JSON data. So, let's first explain to you what is JSON briefly.

What is JSON?

JSON stands for "JavaScript Object Notation" and it is an alternative to XML for transmitting data between a server and web application. It looks like this:

[
    {
        "title": "Post 1", 
        "id": 2, 
        "author": "Rahul", 
        "thumbnail": "image.png"
    }, 
    {
        "title": "Post 2", 
        "id": 3, 
        "author": "Sam", 
        "thumbnail": "image1.png"
    }, 
    {
        "title": "Post 3", 
        "id": 5, 
        "author": "Guest", 
        "thumbnail": "image7.png"
    },
]

How does it work?

You send the request. In return, you get JSON data which you can access like a normal JavaScript object. You can iterate over it, you can manipulate it and play with it. But first, You have to send the request to get it... :0.

Sending requests for getting this JSON data with Axios (first - setting up the environment).

Normally, if you don't want to use external libraries like Axios, and the alternative is the native JavaScript object XMLHttpRequest. However, because of the simplicity of Axios, I prefer using it. Install it:

npm install axios --save

and let's use hooks this time.

import React, { useEffect } from 'react'; 
import axios from 'axios'; 
const comp = () => {
    useEffect(() => {// the alternative to componentDidMount. Here is the right place to send requests and execute code with side effects like the axios code
    }, [])
    return (<div>foo</div>)
}
export default comp;

Sending requests with Axios

Inside the useEffect or componentDidUnMount lifecycle mehtods, we create our requests.

// we call axios.get(/*and here we put the  URL*/) to the page where we're sending the request. 

// In our example, we use ''fake" backend website called JSONplaceholder. If you try the link in your browser, you will see a blank page full of JSX. 
axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
      // Any code here will execute once the data is received. You can access the JSON data you've received this way: 
      response.data
      // to use the data later, set it to the state :)
  })
  .catch(err => {
      // If there's an error with the request, you can handle it here
  })
  .then(() => {
      // always executed
  });

POST-ing data to the server

What if you want to send data to the server, rather than getting it? Then we do a POST request! Your work on the front-end is to send it, then the backend does the most important authentication process and you don't worry about that.

// We use the same configuration as the one for the get request

axios.post('https://jsonplaceholder.typicode.com/posts', 
 {
     // we pass the data we want to send as an object
     firstName: 'Rahul', 
     lastName: 'Singh'
 })
 .then(response => {
     // once the data is sent, we cna get back a response object containing details
 })
 .catch(err => {
     // (optional everywhere) executed if error occurs
 })
 .then(() => {
    //(optional everywhere) Always executed
 })

Delete data from the server

With the DELETE request.

// This starts to get boring... :0 but let's show you how to delete...
let id = this.props.id; // the id of the post we want to delete
axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`)
  .then(response => {
      // once the data is deleted, we can get back a reponse object containing details
  })
  .catch(err => { // (optional everywhere)
  // executed if errors occurs
  })
  .then(() => {// (optional everywhere)
  // always executed 
  });

Of course, that's not everything about Axios. If you want to learn more about it, look at its official GitHub repo.

You can remember axios as "amigos - axios" :0.

Axios is extraordinary, Isn't it ?!๐Ÿ’ป๐Ÿ’ฏ๐Ÿ’ป But suppose somebody hacks your front-end (generally simple) and sends a solicitation containing vindictive code to the server.. ๐Ÿ˜ฐ How might you actually keep this from occurring?

Thanks for Reading.

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!