React 18 Axios Tutorial – Make HTTP GET and POST Requests

Last Updated on by in React JS
In this React Axios tutorial, we are going to learn how to send Axios GET, and POST requests simultaneously using Axios library, React functional components, React Hooks and Node / Express REST APIs.We will create a backend server for handling REST APIs. To build the APIs we will use MongoDB, Node, and Express.js. We will create a frontend using React.js and Bootstrap and check out how to make REST API calls using Axios.

What is Axios?

Almost every web and mobile application retrieve the data when a user makes a request. Web applications get the data from the database when a user makes request.

Most of us every day publish new pictures of our family members, colleagues, and friends on facebook. You must remember when you click on the post button on facebook, and it publishes your data very quickly.

Web services are working behind an app to process the request made by a user. These requests are made through API (Application Programming Interface). The API helps in communicating with the server via a URL in the form of GET, POST, UPDATE, and Delete.

Now, here Axios comes into the light. Axios is a library used to make HTTP requests from the browser via Node and Express.js platform. Axios is a well-known package, and it has got around 63,431 stars on GitHub and forked nearly 5273 times at the time of creating this tutorial.

What Makes Axios Dev-Friendly?

  • Supports the Promise API
  • Make http requests from Node
  • Intercept request and response
  • Transform request and response data
  • Request can be canceled
  • Automatic transforms for JSON data
  • Make XMLHttpRequests from the browser
  • Client-side support for protecting against XSRF

React Axios Tutorial with Example

In this Axios with React tutorial with example, we will create a basic MERN app. This app will have users, and users can be created, retrieved, updated, and deleted from the MongoDB database using Axios.

React Axios HTTP GET, POST Requests Example

  • Step 1: Build React App
  • Step 2: Create Functional Components
  • Step 3: Set up Routes with React Router v6
  • Step 4: Build REST APIs with Node / Express
  • Step 5: Declare Mongoose Schema
  • Step 6: Configure Express Routes
  • Step 7: Configure Server File
  • Step 8: Install & Configure Axios
  • Step 9: Retrieving User Data with Axios GET Request

Set up React App

Run below command to set up React app using official CRA (create-react-app) command.

npx create-react-app react-axios-tutorial

Set up Bootstrap

Run below command to install Bootstrap UI library in React app.

npm install bootstrap --legacy-peer-deps

Add bootstrap.min.css file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
function App() {
  return (
    <div className="App">
      <h2>React Axios Demo</h2>
    </div>
  );
}
export default App;

React app with Bootstrap is ready to be served.

Set up React Component

Go to src directory inside your React project and create a new folder and name it `components`. Inside this folder create the following components.

  • CreateUser.js
  • Users.js

Add code in components/CreateUser.js file:

import React from 'react'
function CreateUser() {
  return (
    <div></div>
  )
}
export default CreateUser

Add code in components/Users.js file:

import React from 'react'
function Users() {
  return (
    <div></div>
  )
}
export default Users

Enable Routing for React Components

Now, we will enable routing for React components.

npm install react-router-dom --legacy-peer-deps

Then, go to src/index.js file and wrap the App directive with the BrowserRouter directive. The BrowserRouter API will enable the routing mechanism in your React app.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

reportWebVitals();

Then, connect the routers with respective components. Go to src/App.js and place the following code inside of it.

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Routes, Route, Link } from "react-router-dom";
import "./App.css";
import CreateUser from "./components/CreateUser";
import Users from "./components/Users";
function App() {
  return (
    <div className="App">
      <nav className="navbar navbar-expand-lg navbar-dark bg-primary">
        <div className="container">
          <span className="navbar-brand">React Axios Tutorial</span>
          <div className="collapse navbar-collapse" id="navbarSupportedContent">
            <ul className="navbar-nav ms-auto">
              <li className="nav-item active">
                <Link className="nav-link" to={"/create-user"}>
                  Create User
                </Link>
              </li>
              <li className="nav-item">
                <Link className="nav-link" to={"/users"}>
                  Users List
                </Link>
              </li>
            </ul>
          </div>
        </div>
      </nav>
      <div className="container">
        <div className="row">
          <Routes>
            <Route exact path="/" element={<CreateUser />} />
            <Route path="/create-user" element={<CreateUser />} />
            <Route path="/users" element={<Users />} />
          </Routes>
        </div>
      </div>
    </div>
  );
}
export default App;

Build REST APIs with Node / Express

Create a separate folder inside the root of the React app and name it server, here we will keep all the server related files.

npm init -y

Install the following dependencies for Node.js.

npm install mongoose express cors body-parser --legacy-peer-deps

Install nodemon NPM package as development dependency to automate the server re-starting process.

npm install nodemon --legacy-peer-deps

Declare Mongoose Schema

Now, create another new folder by the name of models inside the server node backend folder. And also create a file by the name of user-schema.js.

Add the following code in server/models/user-schema.js file.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let userSchema = new Schema({
    name: {
        type: String
    },
    email: {
        type: String
    }
}, {
        collection: 'users'
    })
module.exports = mongoose.model('User', userSchema)

Configure Express Routes

In this step, we will create a separate folder inside the server folder by the name of routes and also create a file by the name of user.routes.js. In this file, we will configure routes for our user’s app.

Add the following code in server/routes/user.routes.js file.

let mongoose = require("mongoose"),
  express = require("express"),
  router = express.Router();
let user = require("../models/user-schema");
router.route("/create").post(async (req, res, next) => {
  await user
    .create(req.body)
    .then((result) => {
      res.json({
        data: result,
        message: "Data added!",
        status: 200,
      });
    })
    .catch((err) => {
      return next(err);
    });
});
router.route("/").get(async (req, res, next) => {
  await user
    .find()
    .then((result) => {
      res.json({
        data: result,
        message: "Data successfully fetched.",
        status: 200,
      });
    })
    .catch((err) => {
      return next(err);
    });
});
router.route("/edit/:id").get(async (req, res, next) => {
  await user
    .findById(req.params.id)
    .then((result) => {
      res.json({
        data: result,
        message: "Data successfully fetched.",
        status: 200,
      });
    })
    .catch((err) => {
      return next(err);
    });
});
router.route("/update/:id").put(async (req, res, next) => {
  await user
    .findByIdAndUpdate(req.params.id, {
      $set: req.body,
    })
    .then((result) => {
      console.log(result);
      res.json({
        data: result,
        msg: "Data successfully updated.",
      });
    })
    .catch((err) => {
      console.log(err);
    });
});
router.route("/delete/:id").delete(async (req, res, next) => {
  await user
    .findByIdAndRemove(req.params.id)
    .then(() => {
      res.json({
        msg: "Data successfully updated.",
      });
    })
    .catch((err) => {
      console.log(err);
    });
});
module.exports = router;

Configure Server File

In this step, we will create server/index.js file and configure following things in it.

  • Define MongoDB database connection.
  • Define server PORT with Express.
  • Node/Express server settings.

Add the following code inside server/index.js file.

let express = require("express");
let mongoose = require("mongoose");
let cors = require("cors");
let bodyParser = require("body-parser");
// Express Route
const studentRoute = require("./routes/student.routes");
// Connecting mongoDB Database
mongoose
  .connect("mongodb://127.0.0.1:27017/test")
  .then((x) => {
    console.log(
      `Connected to Mongo! Database name: "${x.connections[0].name}"`,
    );
  })
  .catch((err) => {
    console.error("Error connecting to mongo", err.reason);
  });
const app = express();
app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: true,
  }),
);
app.use(cors());
app.use("/students", studentRoute);
// PORT
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
  console.log("Connected to port " + port);
});
// 404 Error
app.use((req, res, next) => {
  next(createError(404));
});
app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

To start the node and express server, you must have MongoDB installed on your local development system.

Check out how to install MongoDB community edition on your local machine.

Once the MongoDB community edition has been set up, make sure to start the MongoDB on your local machine then follow the subsequent step.

Open the terminal and execute the following command to invoke the MongoDB web server. It will allow you to save the student data in the database.

npx nodemon server

Here is the base API, where you can see the data is being updated: http://localhost:4000/students

Install & Configure Axios in React

Now, let us get to the business and install the Axios library by running NPM command in the terminal to make the HTTP request in React app.

npm install axios --legacy-peer-deps

Send HTTP POST Request in React

Now, we will use the Axios with React app to make the Axios POST request and send the user data to the MongoDB server.

Update following code in components/CreateUser.js file:

import React, { useState } from "react";
import axios from "axios";
function CreateUser() {
  const [userForm, setUserForm] = useState({
    name: "",
    email: "",
  });
  const onInputChange = (e) => {
    setUserForm((prevNext) => ({
      ...prevNext,
      [e.target.name]: e.target.value,
    }));
  };
  const onSubmit = (e) => {
    e.preventDefault();
    axios
      .post("http://localhost:4000/students/create", userForm)
      .then((res) => {
        setUserForm({
          name: "",
          email: "",
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };
  return (
    <div className="mt-5 wrapper">
      <h2 className="mb-4">React 18 Axios HTTP POST Request Example</h2>
      <form onSubmit={onSubmit}>
        <div className="mb-3">
          <input
            type="text"
            name="name"
            value={userForm.name}
            onChange={onInputChange}
            className="form-control"
            placeholder="name"
          />
        </div>
        <div className="mb-3">
          <input
            type="text"
            name="email"
            value={userForm.email}
            onChange={onInputChange}
            className="form-control"
            placeholder="email"
          />
        </div>
        <div>
          <input
            type="submit"
            value="Create User"
            className="btn btn-success btn-block"
          />
        </div>
      </form>
    </div>
  );
}
export default CreateUser;

We have placed the required HTML and JavaScript logic at its place, now fill the form and create the new user.

This user will be stored in the MongoDB database, we are Making the HTTP call using the Axios POST method in React app.

You can check out your users collection on the following URL locally: http://localhost:4000/students

Retrieving User Data with Axios GET Request

We are going to use one of the most popular HTTP request method that is the axios GET request. The GET method allows to fetch the data from the server with the help of an API.

We can show this data in our React app. We will use the /students API, which we built in this tutorial; however, you can also take the help of free open source REST APIs to consume in your React project.

Let’s hit the server to fetch the users list with Axios GET method.

Update following code in components/Users.js.js file:

import React, { useState, useEffect } from "react";
import axios from "axios";
function Users() {
  const [userForm, setUserForm] = useState([]);
  useEffect(() => {
    axios
      .get("http://localhost:4000/students")
      .then((res) => {
        setUserForm(res.data.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, [userForm]);
  return (
    <div className="mt-5 wrapper">
      <h2 className="mb-4">React 18 Axios HTTP GET Request Example</h2>
      <table className="table">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
          </tr>
        </thead>
        <tbody>
          {userForm.map((user, index) => {
            return (
              <tr key={index}>
                <th scope="row">{user._id}</th>
                <td>{user.name}</td>
                <td>{user.email}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
export default Users;

To run the React app, run the following command:

npm start

Check out your React project on this URL: localhost:3000

Conclusion

Finally, we have completed this React Axios tutorial and learned to make HTTP GET and POST requests using Axios.

Making API call in React is extremely easy because of Axios. We barely scratched the surface in this tutorial, and there are more things which you can do with Axios in regards to make the HTTP calls.

Get the complete code from GitHub, and do not to forget to give it a star.

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.