AppDividend
Latest Code Tutorials

Vue js Axios Tutorial

3,206

Vue js Axios Tutorial is today’s leading topic. 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 which 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 js Axios Tutorial

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 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 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. For that, first, create one component inside 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 that defined 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. 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: Setup a Node.js backend API Endpoint.

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

npm init

Install the following dependencies.

npm install --save express body-parser cors mongoose

Also, install the nodemon as a devDependencies.

Related Posts
1 of 9
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);
});

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 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 this 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 axios module inside AddTicket.vue component.

Vue js Axios Post Example

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 save this data into the database.

Vue js Axios Get Example

Now, we need to display the tickets. So create one component inside 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 vue application. So go 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 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 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 component 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 the 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

Leave A Reply

Your email address will not be published.