How to Use Axios with Vue.js

Here are the steps to use Axios with Vue.js.

Step 1: Install Vue.js.

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

npm install -g @vue/cli

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.

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>

Import this component inside the 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 I have defined one routes object, an array of different routes with its component, and passed 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.

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>

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>

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

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);
});

We must create and connect the MongoDB database with our express application.

Note: You must have installed the MongoDB database on your server or locally; otherwise, you must download it and start the MongoDB server.

Create one config folder inside the 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.

We must 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);

Define the two routes for our application: 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;

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.

Install the axios via the following command.

yarn add axios vue-axios

Use this module inside the src  >>  main.js file.

// main.js

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

Vue.use(VueAxios, axios);

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

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>

Register this component and its route inside the vue application. So go to the main.js file, 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>

Go to http://localhost:8080/index. You can see that we can 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

That’s it!

3 thoughts on “How to Use Axios with Vue.js”

  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.