简体   繁体   中英

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.

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 => ...)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM