React Axios Tutorial – Make HTTP GET and POST Requests

By Digamber Rawat Last updated on
In this React Axios tutorial, we are going to learn how to make Axios GET, and POST requests using Axios. I will create a backend server for React app using MongoDB, Node, and Express.js. We will create a frontend using React.js and Bootstrap 4. Then, we will learn 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.

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

To run the React app, run the following command:

npm start

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

Set up Bootstrap 4

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

npm install bootstrap --save

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 4 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.

  • create-user.component.js
  • users.component.js
// ** create-user.component.js ** //

import React, { Component } from 'react';

export default class CreateUser extends Component {
    render() {
        return (
            <div>
                <p>Create User Component!!</p>
            </div>
        )
    }
}
// ** users.component.js ** //

import React, { Component } from 'react';

export default class Users extends Component {
    render() {
        return (
            <div>
                <p>Users Component!!</p>
            </div>
        )
    }
}

Enable Routing for React Components

Now, we will enable routing for React components.

npm install react-router-dom --save

Then, go to src/index.js file add the following code in the file.

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";

import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
    document.getElementById("root")
);

serviceWorker.unregister();

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 '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

import CreateUser from "./components/create-user.component";
import Users from "./components/users.component";

function App() {
  return (<Router>
    <div className="App">
      <header>
        <nav className="navbar navbar-expand-lg navbar-dark bg-primary">
          <a className="navbar-brand">React Axios Tutorial</a>

          <div className="collapse navbar-collapse" id="navbarSupportedContent">
            <ul className="navbar-nav ml-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>
        </nav>
      </header>

      <div className="container">
        <div className="row">
          <div className="col-md-12">
            <Switch>
              <Route exact path='/' component={CreateUser} />
              <Route path="/create-user" component={CreateUser} />
              <Route path="/users" component={Users} />
            </Switch>
          </div>
        </div>
      </div>
    </div>
  </Router>
  );
}

export default App;

Create User Form with Bootstrap 4 in React

Here, we will create a user form using Bootstrap 4 UI component. Go to src/components/create-user.component.js file and add the following code.


import React, { Component } from 'react';

export default class CreateUser extends Component {
    render() {
        return (
            <div className="wrapper">
                <form>
                    <div className="form-group">
                        <label>Enter Name</label>
                        <input type="text" className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>Enter Email</label>
                        <input type="text" className="form-control" />
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Create User" className="btn btn-success btn-block" />
                    </div>
                </form>
            </div>
        )
    }
}

Build Node Server With Express and MongoDB

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

Install the following dependencies for Node.js.

npm install mongoose express cors body-parser

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

npm install nodemon --save-dev

Set up MongoDB Database Connection

Create a new folder by the name of database inside the server folder, and also create a file by the name of db.js in this file we will keep MongoDB database settings. Paste the following code in the server/database/db.js file.

module.exports = {
    db: 'mongodb://localhost:27017/reactaxios'
};

We will declare the database in server.js file in upcoming steps.

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((req, res, next) => {
    user.create(req.body, (error, data) => {
        if (error) {
            return next(error)
        } else {
            console.log(data)
            res.json(data)
        }
    })
});

router.route('/').get((req, res) => {
    user.find((error, data) => {
        if (error) {
            return next(error)
        } else {
            res.json(data)
        }
    })
})

router.route('/edit/:id').get((req, res) => {
    user.findById(req.params.id, (error, data) => {
        if (error) {
            return next(error)
        } else {
            res.json(data)
        }
    })
})


router.route('/update/:id').put((req, res, next) => {
    user.findByIdAndUpdate(req.params.id, {
        $set: req.body
    }, (error, data) => {
        if (error) {
            return next(error);
            console.log(error)
        } else {
            res.json(data)
            console.log('User updated successfully !')
        }
    })
})

router.route('/delete/:id').delete((req, res, next) => {
    user.findByIdAndRemove(req.params.id, (error, data) => {
        if (error) {
            return next(error);
        } else {
            res.status(200).json({
                msg: data
            })
        }
    })
})

module.exports = router;

Configure Server.js in React App

In this step, we will create server/server.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/server.js file.

let express = require('express');
let mongoose = require('mongoose');
let cors = require('cors');
let bodyParser = require('body-parser');
let database = require('./database/db');


const userRoute = require('../server/routes/user.routes')


mongoose.Promise = global.Promise;
mongoose.connect(database.db, {
    useNewUrlParser: true
}).then(() => {
    console.log('Database connected sucessfully !')
},
    error => {
        console.log('Database could not be connected : ' + error)
    }
)

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cors());
app.use('/users', userRoute)


const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
    console.log('Connected to port ' + port)
})

// Error Handling
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);
});

We are all set with our node, express server along with mongoDB database.

Let us start the mongoDB, run the below command in the terminal.

mongod

Open, another terminal and start the nodemon server by running the following command:

nodemon server

# [nodemon] 1.19.1
# [nodemon] to restart at any time, enter `rs`
# [nodemon] watching: *.*
# [nodemon] starting `node server`
# Connected to port 4000
# Database connected sucessfully !

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 --save

Make Axios POST Request in MERN Stack

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

// ** create-user.component.js ** //

import React, { Component } from 'react';
import axios from 'axios';

export default class CreateUser extends Component {

    constructor(props) {
        super(props)

        this.onChangeUserName = this.onChangeUserName.bind(this);
        this.onChangeUserEmail = this.onChangeUserEmail.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: '',
            email: ''
        }
    }

    onChangeUserName(e) {
        this.setState({ name: e.target.value })
    }

    onChangeUserEmail(e) {
        this.setState({ email: e.target.value })
    }

    onSubmit(e) {
        e.preventDefault()

        const userObject = {
            name: this.state.name,
            email: this.state.email
        };

        axios.post('http://localhost:4000/users/create', userObject)
            .then((res) => {
                console.log(res.data)
            }).catch((error) => {
                console.log(error)
            });

        this.setState({ name: '', email: '' })
    }


    render() {
        return (
            <div className="wrapper">
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Add User Name</label>
                        <input type="text" value={this.state.name} onChange={this.onChangeUserName} className="form-control" />
                    </div>
                    <div className="form-group">
                        <label>Add User Email</label>
                        <input type="text" value={this.state.email} onChange={this.onChangeUserEmail} className="form-control" />
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Create User" className="btn btn-success btn-block" />
                    </div>
                </form>
            </div>
        )
    }
}

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/users

Retrieving User Data with Axios GET Request

We are going to use one of the most popular HTTP requests, which is none other than the GET request. The GET method allows us 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 /users 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.

Add the following code in components/users.component.js file.

import React, { Component } from 'react';
import axios from 'axios';
import DataTable from './data-table';

export default class Users extends Component {

    constructor(props) {
        super(props);
        this.state = { usersCollection: [] };
    }

    componentDidMount() {
        axios.get('http://localhost:4000/users')
            .then(res => {
                this.setState({ usersCollection: res.data });
            })
            .catch(function (error) {
                console.log(error);
            })
    }

    dataTable() {
        return this.state.usersCollection.map((data, i) => {
            return <DataTable obj={data} key={i} />;
        });
    }

    render() {
        return (
            <div className="wrapper-users">
                <div className="container">
                    <table className="table table-striped table-dark">
                        <thead className="thead-dark">
                            <tr>
                                <td>ID</td>
                                <td>Name</td>
                                <td>Email</td>
                            </tr>
                        </thead>
                        <tbody>
                            {this.dataTable()}
                        </tbody>
                    </table>
                </div>
            </div>
        )
    }
}

Then, create another component in src/components folder and name it data-table.js. Add the following code inside of this file.

import React, { Component } from 'react';

class DataTable extends Component {
    render() {
        return (
            <tr>
                <td>
                    {this.props.obj._id}
                </td>
                <td>
                    {this.props.obj.name}
                </td>
                <td>
                    {this.props.obj.email}
                </td>
            </tr>
        );
    }
}

export default DataTable;

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. I hope you loved this article. Please share this tutorial with others.

Git Repo

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me