Qwertie
Qwertie

Reputation: 6513

Send HTML form via axios

In my vue app I have a regular <form> when I hit submit it sends the right data but it doesn't set the authentication headers on the request. I have axios configured to attach these headers on every request so I need to send the data via axios.

From the axios docs I know I can post data like this

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })

and I also know I can run a custom function on a form post by adding @submit.prevent="handleSubmit to the <form> tag.

What I can't work out is how to get all the values from the form inputs and send it via axios.

Upvotes: 4

Views: 3684

Answers (1)

Brian Lee
Brian Lee

Reputation: 18187

In your handleSubmit function, you can use the FormData class like:

handleSubmit (event) {
    event.preventDefault()
    let formData = new FormData(event.target)
    axios.post('/user', formData).then(response => ...).catch(error => ...)
}

Upvotes: 5

Related Questions