AppDividend
Latest Code Tutorials

React Axios Tutorial Example From Scratch

Axios GET and POST request Tutorial in React.js

7,643

Get real time updates directly on you device, subscribe now.

In this demo project, I will show you how to create React Axios Tutorial Example from scratch. For this example, I will use Node.js, Express.js, and MongoDB as a backend server, framework, and database. On the frontend, I will use React.js and Bootstrap. In every project,  we need to create a REST API at some stage. Axios is a lightweight HTTP client based similar to a Fetch API.

Axios is promise-based async/await library for the readable asynchronous code. We can easily integrate with React.js, and it is effortless to use in any frontend framework.

If you want to learn more about React.js then check out this  React 16 – The Complete Guide (incl. React Router 4 & Redux) Guide. It has a very brief intro about React and Redux.
React 16 – The Complete Guide (incl. React Router 4 & Redux)

React Axios Tutorial Example

We start this example by installing the React.js using create-react-app.

Step 1: Install React.js

Install create-react-app globally using the following command. You need to enter this command in admin mode.

npm install -g create-react-app
create-react-app reactaxios

React Axios Tutorial Example From Scratch

Step 2: Install Bootstrap 4.

Install Bootstrap 4 using the following command.

npm install bootstrap --save

Include bootstrap.min.css file inside App.js file.

// App.js

import React, { Component } from 'react';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {
  render() {
    return (
      <div class="container">
        React Axios Tutorial
      </div>
    );
  }
}

export default App;

Okay, now we have successfully integrated Bootstrap 4.

Step 3: Create React components.

Inside the src folder, create a new folder called components.

Okay, inside components folder, create two components.

  1. Create.js
  2. Index.js
// Create.js

import React, { Component } from 'react';

export default class Create extends Component {
    render() {
        return (
            <div>
                <p>Welcome to Create Component!!</p>
            </div>
        )
    }
}
// Index.js

import React, { Component } from 'react';

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

Step 4: Create Routing of the components.

Install the following routing library.

npm install react-router-dom --save

Go to index.js file and Wrap the BrowserRouter object around App.js component.

// App.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

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

Now, define the routes for each component.

// App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Create from './components/Create';
import Index from './components/Index';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {
  render() {
    return (
      <Router>
        <div className="container">
          <h2>Welcome to React Express Tutorial</h2>
          <ul>
            <li><Link to={'/create'}>Create</Link></li>
            <li><Link to={'/index'}>List</Link></li>
          </ul>
          <hr />
          <Switch>
              <Route exact path='/create' component={ Create } />
              <Route path='/index' component={ Index } />
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

Now, go to this URL: http://localhost:3000/create.

Axios React Example

 

Step 5: Create a Navigation bar.

Okay, now write the following code inside App.js file.

// App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Create from './components/Create';
import Index from './components/Index';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

class App extends Component {
  render() { 
    return (
      <Router>
        <div className="container">
          <nav className="navbar navbar-expand-lg navbar-light bg-light">
            <a className="navbar-brand">React Express App</a>
            <div className="collapse navbar-collapse" id="navbarSupportedContent">
              <ul className="navbar-nav mr-auto">
                <li className="nav-item"><Link to={'/create'} className="nav-link">Create</Link></li>
                <li className="nav-item"><Link to={'/index'} className="nav-link">List</Link></li>
              </ul>
              <hr />
            </div>
          </nav> <br />
          <Switch>
              <Route exact path='/create' component={ Create } />
              <Route path='/index' component={ Index } />
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

Step 6: Create a Bootstrap 4 Form.

Add the HTML Form code inside Create.js.

Related Posts
1 of 20
// Create.js

import React, { Component } from 'react';

export default class Create extends Component {
    render() {
        return (
            <div style={{marginTop: 50}}>
                <h3>Add New Server</h3>
                <form>
                    <div className="form-group">
                        <label>Add Host Name:  </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <label>Add Server Port: </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Add Node server" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

Step 7: Submit The Create.js Form.

So, now we have two fields.

  1. server name
  2. server port

So we need to create two functions that can track both the values and set the state according to it. Also, create the third function that will send the POST request to the node.js server.

Now, I need to create an event that tracks the state of both the input types.

Finally, when we click the submit button, then data is provided to the server.

// Create.js

import React, { Component } from 'react';

export default class Create extends Component {

    constructor(props) {
        super(props);
        this.onChangeHostName = this.onChangeHostName.bind(this);
        this.onChangePort = this.onChangePort.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: '',
            port: ''
        }
    }
    onChangeHostName(e) {
        this.setState({
            name: e.target.value
        });
    }
    onChangePort(e) {
        this.setState({
            port: e.target.value
        });
    }
    onSubmit(e) {
        e.preventDefault();
        console.log(`name is ${this.state.name} and port is ${this.state.port}`);
        this.setState({
            name: '',
            port: ''
        })
    }

    render() {
        return (
            <div style={{marginTop: 50}}>
                <h3>Add New Server</h3>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                        <label>Add Host Name:  </label>
                        <input type="text" className="form-control" value={this.state.name}  onChange={this.onChangeHostName}/>
                    </div>
                    <div className="form-group">
                        <label>Add Server Port: </label>
                        <input type="text" className="form-control" value={this.state.port}  onChange={this.onChangePort}/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Add Node server" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

Step 8: Create backend Node.js server.

First, start the mongodb database server using the following command.

mongod

In the root folder, create one file called server.js.

Now, install the following node.js dependencies.

npm install express nodemon body-parser cors mongoose --save

Also, we need to install nodemon as a development dependency.

npm install nodemon --save-dev

Okay, now write the following code inside a server.js file.

// server.js

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.listen(PORT, function(){
  console.log('Server is running on Port: ',PORT);
});

Now, create a DB.js file inside root folder.

// DB.js

module.exports = {
    DB: 'mongodb://localhost:27017/axios'
}

Now, import this DB.js file into the server.js file and connect a node.js application to the mongodb database.

// server.js

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');
const config = require('./DB');

mongoose.connect(config.DB).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database' +err)
});

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.listen(PORT, function(){
  console.log('Server is running on Port: ',PORT);
});

Now open the terminal, and you can see that our database is connected with our Node Express application.

Step 9: Create a Mongoose schema.

Create one folder inside root called models and inside that create one file called ServerPort.js

// ServerPort.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for ServerPort
const ServerPort = new Schema({
  name: {
    type: String
  },
  port: {
      type: Number
  }
},{
    collection: 'servers'
});

module.exports = mongoose.model('ServerPort', ServerPort);

Step 10: Create Express Routes.

Create one folder called routes. Inside that routes folder, create one file called ServerPortRouter.js.

// ServerPortRouter.js

const express = require('express');
const app = express();
const ServerPortRouter = express.Router();

const ServerPort = require('../models/ServerPort');

ServerPortRouter.route('/add').post(function (req, res) {
  const serverport = new ServerPort(req.body);
  serverport.save()
    .then(serverport => {
        res.json('Server added successfully');
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

ServerPortRouter.route('/').get(function (req, res) {
    ServerPort.find(function (err, serverports){
    if(err){
      console.log(err);
    }
    else {
      res.json(serverports);
    }
  });
});

module.exports = ServerPortRouter;

Here, I have defined both GET and POST request routes.

I have used Mongoose ORM to save the data in MongoDB database.

The final step is to import the ServerPortRouter.js file inside the server.js file.  The server.js file looks like below.

// server.js

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const PORT = 4000;
const cors = require('cors');
const config = require('./DB');
const ServerPortRouter = require('./routes/ServerPortRouter');

mongoose.connect(config.DB).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database' +err)
});

app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use('/serverport', ServerPortRouter);

app.listen(PORT, function(){
  console.log('Server is running on Port: ',PORT);
});

Step 11: Install Axios Library.

Okay, we will install Axios via npm using the following command.

npm install axios --save

Now, send the post request along with the form data to the node and express server.

First, we need to import the axios library inside Create.js and use that library to send a POST request.

// Create.js

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

export default class Create extends Component {

    constructor(props) {
        super(props);
        this.onChangeHostName = this.onChangeHostName.bind(this);
        this.onChangePort = this.onChangePort.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: '',
            port: ''
        }
    }
    onChangeHostName(e) {
        this.setState({
            name: e.target.value
        });
    }
    onChangePort(e) {
        this.setState({
            port: e.target.value
        });
    }
    onSubmit(e) {
        e.preventDefault();
        const serverport = {
            name: this.state.name,
            port: this.state.port
        }
        axios.post('http://localhost:4000/serverport/add', serverport)
        .then(res => console.log(res.data));
        
        this.setState({
            name: '',
            port: ''
        });
    }

    render() {
        return (
            <div style={{marginTop: 50}}>
                <h3>Add New Server</h3>
                <form>
                    <div className="form-group">
                        <label>Add Host Name:  </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <label>Add Server Port: </label>
                        <input type="text" className="form-control"/>
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Add Node server" className="btn btn-primary"/>
                    </div>
                </form>
            </div>
        )
    }
}

Now, enter the values and submit the form.  Open your browser console panel and see the response.

React js Axios POST example

 

We can that values are saved in the MongoDB database.

MERN Stack Example

 

Step 12: Send Axios GET request.

Write the following code inside Index.js file.

// Index.js

import React, { Component } from 'react';
import axios from 'axios';
import TableRow from './TableRow';

export default class Index extends Component {

  constructor(props) {
      super(props);
      this.state = {serverports: []};
    }
    componentDidMount(){
      axios.get('http://localhost:4200/serverport')
      .then(response => {
        this.setState({ serverports: response.data });
      })
      .catch(function (error) {
        console.log(error);
      })
    }
    tabRow(){
        return this.state.serverports.map(function(object, i){
            return <TableRow obj={object} key={i} />;
        });
    }

    render() {
      return (
        <div className="container">
            <table className="table table-striped">
              <thead>
                <tr>
                  <td>ID</td>
                  <td>Name</td>
                  <td>Port</td>
                </tr>
              </thead>
              <tbody>
                {this.tabRow()}
              </tbody>
            </table>
        </div>
      );
    }
  }

Okay, now write the stateless component, and that is TableRow.js component, which we need to create inside components folder.

// TableRow.js

import React, { Component } from 'react';

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

export default TableRow;

Okay, now go to the http://localhost:3000/index

We can see that we have successfully sent an Axios GET request from React.js component.

So, in this example, we have seen axios get and post request.

Finally, React Axios Tutorial Example is over. Thanks for taking.

Github Code

Steps to use Github Code

  1. Start the MongoDB server using this command: mongod
  2. Clone The Repository. Go into the project folder.
  3. Install all the dependencies using this command: npm install
  4. Start the Node.js server using this command: nodemon server
  5. Start the react.js development server using this command: yarn start
  6. Go to this URL: http://localhost:3000/create
4 Comments
  1. kate spade iphone 8 plus case says

    This is my first time pay a visit at here and i am truly pleassant
    to read all at alone place.

  2. Brian says

    Thanks. A good help.

  3. Cristiane Abreu says

    Thank you very much for this tutorial Krunal, I followed your instruction but I could not see the data on the mongo db on my Robo 3t, where can I see your repo so I can compare my code to your and see where I am doing the erros. Also I did not see axios db on the tutorial , just DB. Thank you very much

  4. Musaddiq says

    Please also make your videos same as articals

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.