1

i'm trying to send image in form data to API node.js server but it's give me error every time console.log(fd.getAll('image')[0])

it came with correct File,

here's my HTML code

<form @submit.prevent>
<input type="text" placeholder="اسم القسم" v-model="name">
<input type="file" @change="fileSelected">
<button @click="addCategory" class="button--edit">اضف قسم جديد</button>
</form>

javascript code :

fileSelected(event){
  this.selectedFile = event.target.files[0]
},
addCategory(){
 const token = this.$store.state.idToken.token;
 const file = this.selectedFile;
 const fd = new FormData();
 const name = this.name
 fd.append('image', file); 
 //console.log(fd.getAll('image')[0])
    axios({
        method: 'post',
        url: '/admin/support/catigory',
        data: {
          image: fd,
          name: name
        },
        headers: {
        'Authorization': `Basic ${token}`,
        }
    })
    .then(res => {
        console.log(res)
    })
    .catch(err => {
      console.log(err.response)
    })
}

here is the back-end function :

exports.postRoute = async (req, res, next) => {
const name = req.body.name;
const image = req.files;  
const errors = validationResult(req);
  try {
if (!errors.isEmpty()) {
const error = new Error(
`validation faild for ${errors.array()[0].param} in the ${
errors.array()[0].location
}`
);
error.statusCode = 422;
throw error;
}
if (image.length == 0) {
const error = new Error("validation faild.. you should insert image");
error.statusCode = 422;
throw error;
 }

here is the error: error in console

also i had tried to add :

'Content-Type': `multipart/form-data` to the herders but nothing changed
  • Append `name` to your `FormData` instance (`fd.append('name', name)`) and send that as the request payload, ie `data: fd`. Also, do **not** set a `Content-Type` header. Your browser will do this automatically for you when you POST a `FormData` instance – Phil Jul 02 '20 at 00:14
  • 1
    Does this answer your question? [Send FormData object AND an additional parameter via ajax](https://stackoverflow.com/questions/36448724/send-formdata-object-and-an-additional-parameter-via-ajax). I know it's about jQuery but the solution is the same – Phil Jul 02 '20 at 00:17
  • i've tried to append name but also it became empty object in the body of request code : fd.append('image', file); fd.append('name', name); axios({ method: 'post', url: '/admin/support/catigory', data: { fd }, headers: { 'Authorization': `Basic ${token}`, } }) – Mohamed Karawia Jul 02 '20 at 00:33
  • 1
    No, not `data: { fd }`, `data: fd`. You can also use the shorter version `axios.post('/admin/support/catigory', fd, { headers: { Authorization: \`Basic ${token}\` } })` – Phil Jul 02 '20 at 00:35
  • it worked. thank you so much – Mohamed Karawia Jul 02 '20 at 00:44

0 Answers0