Vue Axios Example: The Complete Guide Step by Step

Axios is an excellent http client library. It uses promises by default and runs on both the client and the server. Axios is an impressive HTTP client library that lets you asynchronously issue HTTP requests to interact with REST endpoints. Consume REST APIs and make HTTP Requests is easy with Axios and Vue.js.

Vue Axios

We will use Axios to send an HTTP request to the Node.js server and fetch the data from the database and display it on the client-side. We will make GET and POST request to the Node.js server. At the backend, we will use the Express web framework. Okay, so first, we need to install Vue.js using CLI. If you are not familiar with Vue cli, then please check out this Vue cli Tutorial.

Step 1: Install Vue.js.

If you have not installed the vue cli, then type the following command.

npm install -g @vue/cli

Now type the command to generate the Vue project.

 vue create vueaxiospro

It will create a necessary boilerplate for us to work with it.

Step 2: Install the Vue-router package.

Go to the command line terminal and type the following command.

npm install vue-router --save

It will install the module and update the package.json file.

Now, we need to configure the vue-router for our application. First, create one component inside the components directory and call that file AddTicket.vue.

// AddTicket.vue

<template>
  <div>Add Ticket</div> 
</template>
<script>
export default {
  
}
</script>

Now, import this component inside src  >>  main.js file. Also include the Vue-router module inside the main.js file as well. So we can define and register our routes to the Vue application.

// main.js

import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
import AddTicket from './components/AddTicket.vue';
Vue.use(VueRouter);

const routes = [
  {
        name: 'add',
        path: '/add',
        component: AddTicket
  }
];
const router = new VueRouter({ mode: 'history', routes: routes });

Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

So what I have done is define one routes object, which is an array of different routes with its component, and pass that object to the VueRouter module. Now that whole object is registered to the Vue application. So if you switch to this URL: http://localhost:8080/add, You can see our /add route is working.

Step 3: Create a bootstrap form to add the ticket.

Now, add the following code inside AddTicket.vue file.

<template>
  <div class="container">
    <h1>Create A Ticket</h1>
    <form v-on:submit.prevent="addTicket">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label>Email ID:</label>
            <input type="text" class="form-control" v-model="ticket.email"/>
          </div>
        </div>
        </div>
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>Ticket Description:</label>
              <textarea cols="5" rows="5" class="form-control col-md-6" v-model="ticket.description"></textarea>
            </div>
          </div>
        </div><br />
        <div class="form-group">
          <button class="btn btn-primary">Create Ticket</button>
        </div>
    </form>
  </div>
</template>
<script>
export default {
    data(){
        return {
          ticket: {}
        }
    },
    methods: {
       addTicket() {
            alert('clicked');
       }
    }
}
</script>

Also, add the Bootstrap CDN inside the public  >>  index.html file.

<!-- index.html -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="shortcut icon" href="<%= webpackConfig.output.publicPath %>favicon.ico">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
    <title>vueaxios</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

Now, you can see that our bootstrap classes are working on our form.

 

vue axios post example

Step 4: Set up a Node.js backend API Endpoint.

Create a new folder outside the vue project called exp-api. Inside that folder, first, create a package.json file by typing the following command.

npm init

Install the following dependencies.

npm install --save express body-parser cors mongoose

Also, install the nodemon as a devDependencies.

npm install --save-dev nodemon

Add the start script inside a package.json file.

"scripts": {
    "start": "nodemon server.js"
  },

Create a server.js file inside the project root and add the following code inside a server.js file.

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

mongoose.Promise = global.Promise;
mongoose.connect(config.DB);
      
const app = express();
var port = process.env.PORT || 4000;

app.listen(port, function(){
  console.log('Node js Express js Tutorial at port', port);
});

The next thing is we need to create the MongoDB database and connect it with our express application.

Note: You need to have installed MongoDB database on your server or local otherwise, first, you need to download it and start the MongoDB server.

Create one config folder inside project root. In that, create one file called DB.js.

// DB.js

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

Step 5: Create Express web routes for our application.

Now, we need to create two folders inside a root called exproutes and models.

In the models folder, create one model called Ticket.js.

// Ticket.js

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

// Define collection and schema for Items
var Ticket = new Schema({
  email: {
    type: String
  },
  description: {
    type: String
  }
},{
    collection: 'tickets'
});

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

Now, define the two routes for our application, and that is GET and POST.

So inside the exproutes folder, make one file called ticket.route.js file.

// ticket.route.js

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

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

ticketRoutes.route('/add').post(function (req, res) {
   var ticket = new Ticket(req.body);
       ticket.save()
     .then(ticket => {
     res.status(200).json({'ticket': 'ticket added successfully'});
     })
     .catch(err => {
     res.status(400).send("unable to save to database");
     });
 });

 ticketRoutes.route('/').get(function (req, res) {
   Ticket.find(function (err, tickets){
     if(err){
       console.log(err);
     }
     else {
       res.json(tickets);
     }
   });
 });
 
 module.exports = ticketRoutes;

Now, register these routes to the Express web application. So our final server.js file looks like this.

// server.js

const express = require('express');
const  path = require('path');
const  bodyParser = require('body-parser');
const  cors = require('cors');
const  mongoose = require('mongoose');
const  config = require('./config/DB');
const ticketRoutes = require('./exproutes/ticket.route');

mongoose.Promise = global.Promise;
mongoose.connect(config.DB);
      
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/tickets', ticketRoutes);
var port = process.env.PORT || 4000;

app.listen(port, function(){
  console.log('Node js Express js Tutorial at port', port);
});

Step 6: Set up an axios in a Vue.js application.

First, install the axios via the following command.

yarn add axios vue-axios

Now, use this module inside src  >>  main.js file.

// main.js

import axios from 'axios';
import VueAxios from 'vue-axios';

Vue.use(VueAxios, axios);

Now, we can use the axios module inside AddTicket.vue component.

Vue Axios Post

Write the following code inside AddTicket.vue file.

// AddTicket.vue

methods: {
       addTicket() {
             let uri = 'http://localhost:4000/tickets/add';
            this.axios.post(uri, this.ticket).then((response) => {
               console.log(response);
            });
       }
    }

We have used axios’s post method to send the data to the Node.js server. Node.js then saves this data into the database.

Vue Axios Get

Now, we need to display the tickets. So create one component inside the components folder called TicketView.vue.

// TicketView.vue

<template>
    <div class="container">
        <h1>Tickets</h1>
        <table class="table table-hover">
            <thead>
            <tr>
                <td>ID</td>
                <td>Email ID</td>
                <td>Description</td>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</template>

<script>

    export default {
        data(){
            return{
                items: []
            }
        },

        methods: {
           
        }
    }
</script>

Now, register this component and its route inside the vue application. So go to the main.js file and import this component and add it to the routes array.

// main.js

import TicketView from './components/TicketView.vue';

const routes = [
  {
        name: 'add',
        path: '/add',
        component: AddTicket
  },
  {
    name: 'index',
    path: '/index',
    component: TicketView
}
];

Fetch the data using the axios get method.

// TicketView.vue

<script>

    export default {
        data(){
            return{
                tickets: []
            }
        },

        created: function()
        {
            this.fetchItems();
        },

        methods: {
            fetchItems()
            {
              let uri = 'http://localhost:4000/tickets';
              this.axios.get(uri).then((response) => {
                  this.tickets = response.data;
              });
            }
        }
    }
</script>

We have used the Lifecycle method called created(). When this component loads, this method is by default called. So we have to fetch the data at that time. So after the component is built, we can get the data from the server. Now, display the data.

// TicketView.vue

<template>
    <div class="container">
        <h1>Tickets</h1>
        <table class="table table-hover">
            <thead>
            <tr>
                <td>ID</td>
                <td>Email ID</td>
                <td>Description</td>
            </tr>
            </thead>
            <tbody>
               <tr v-for="ticket in tickets" :key="ticket._id">
                    <td>{{ ticket._id }}</td>
                    <td>{{ ticket.email }}</td>
                    <td>{{ ticket.description }}</td>
                    <td></td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script>

    export default {
        data(){
            return{
                tickets: []
            }
        },

        created: function()
        {
            this.fetchItems();
        },

        methods: {
            fetchItems()
            {
              let uri = 'http://localhost:4000/tickets';
              this.axios.get(uri).then((response) => {
                  this.tickets = response.data;
              });
            }
        }
    }
</script>

Okay, now go to http://localhost:8080/index. You can see that we can able to fetch the data from the database. So this is how you can use Axios Promise-based library. Finally, our Vue js Axios Tutorial is over.

Github Code for Node.js API

Github Code For Vue Axios Project

3 thoughts on “Vue Axios Example: The Complete Guide Step by Step”

  1. how do you post de data if you have a onetoone relationship between “ticket” and suposed “reservation”,and you pick the data from the same form,how you send ticket.id ,ticket.email , ticket.description and reservation.number all in the same json?

    Reply

Leave a Comment

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