Simon Cooper
Simon Cooper

Reputation: 1594

Can't Submit Axios Post form Nuxt.js (VueJS)

I'm playing around with my first ever form in Vue. I've created my app with Nuxt.

I'm able to get data via an axios get request from my API but I can't seem to post data.

new.vue

<template>
    <section class="container">
    <div>
        <h1>Gins</h1>
        <form @submit.prevent="addGin">
        <h4>New Product</h4>
        <p>
            <label for="name" class="input-label">Title:</label>
            <input id="name" v-model="title" type="text" name="name" class="input">
        </p>
        <p>
            <button type="submit" value="Submit" class="button">Add Gin</button>
        </p>
        </form>
    </div>
    </section>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    return {
      title: '',
      errors: []
    }
  },

  methods: {
    addGin() {
      axios.post('/apv/v1/gins', this.title)
        .then((Response) => {})
        .catch((err) => {
          this.errors.push(err)
        })
    }
  }
}
</script>

When clicking the submit button, I'm not receiving any errors, but I can confirm no entry is added to my API database.

My API is running on a different server localhost:4000 and I have set up the proxy in nuxt.config.js

 axios: {
    proxy: true
  },
  proxy: {
    '/api/v1/': 'http://localhost:4000'
  },

I've experimented with both <form @submit.prevent="addGin"> and <form v-on:submit.prevent="addGin"> but this doesn't seem to make a difference.

What else might I be missing?

Upvotes: 1

Views: 10703

Answers (2)

Simon Cooper
Simon Cooper

Reputation: 1594

OK so was really close. Changing my axios params to title: this.title, apparently did the trick.

Upvotes: 0

gleam
gleam

Reputation: 870

  1. Add @nuxtjs/axios module into modules part of nuxt.config
  2. Use this.$axios instead of imported one. Proof: https://axios.nuxtjs.org/usage

Upvotes: 1

Related Questions