Vue Problems — Getters with Arguments, Post Request with Form Data, and More
Vue.js makes developing front end apps easy. However, there are still chances that we’ll run into problems.
In this article, we’ll look at some common issues and see how to solve them.
Making POST Requests with Form Data with Axios
We can make POST requests with form data by passing the FormData
object as the 2nd argument of the post
method.
For instance, we can write:
...
const rawData = {
firstName: this.firstName,
lastName: this.lastName
}const formData = new FormData()
formData.append('avatar', this.file, this.file.name)
formData.append('data', rawData)try {
const response = await axios.post('http://localhost:3003/api/test.php', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
...
We have the FormData
instance, which has a file object with the key 'avatar'
.
Also, we added data with the key 'rawData'
into the code.
Then we called axios.post
on to send the form data with the request.
The headers
property has to set with 'Content-Type'
key set to 'multipart/form-data'
to send the data with…