Vue axios post request example

In this post, we will explain how to send http request using axios in vue.js. We will send vue axios post request with parameter as array of form data in vue cli npm app. Here get simple example of axios post request in vue.js app from scratch.

Installing axios from npm

With the npm CLI: npm install axios

With the yarn CLI: yarn add axios

Vue axios post request with JSON body

We always choose axios to call api in vue js application. Vue axios is a http client library and axios provide to send get, post, put, delete request with parameter, formdata, heades, string, image, multipart/form-data etc. Vue axios best library for http requests.

In this example, we will create simple form with two input fields in vue.js. We will form submit request by using axios http post request following input parameters.

So, let’see below example step to create one POST request api for the this example.

Step 1: Create Vue.js App

In this step, we need to create vue cli app using below command.

vue create my-app
Step 2: Install vue-axios package

Here, we need to install vue-axios npm package for send post request using axios.

npm install --save axios vue-axios
Example code

Here, we will create HelloWord.vue component with following code.

<template>
  <div>
    <h1>Create Post</h1>
    <form @submit.prevent="createPost">
      <div>
        <label for="title">Title:</label>
        <input type="text" id="name" v-model="title" />
      </div>

      <div>
        <label for="title">Description:</label>
        <textarea
          name="description"
          id="description"
          cols="30"
          rows="10"
          v-model="description"
        ></textarea>
      </div>
      <button type="submit">Submit</button>
    </form>
    <p v-if="responseMessage">{{ responseMessage }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      title: "",
      description: "",
      responseMessage: ""
    };
  },
  methods: {
    async createPost() {
      try {
        const response = await axios.post('http://localhost:8000/yourPostApi',{
          title: this.title,
          description: this.description
        });
        console.log(response.data);
        this.responseMessage = "Post created";
    } catch (error) {
      this.responseMessage = "Error creating post";
      console.error(error);
    }
  },
},
};
</script>

Now, you can run vue app by using following command

npm run serve

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *