reactjsrtk-query

send form data with rtk query


I wanna send an image with form data to the nest js server with RTK query but the file didn't send. the code are:

    uploadImage: builder.mutation<any, any>({
  query: (imageFile) => {
    var bodyFormData = new FormData();
    bodyFormData.append('file', imageFile);
    console.log({ bodyFormData, imageFile });
    return {
      url: '/uploader/image',
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data;'
      },
      body: { bodyFormData }
    };
  }
})

I can send an image with Axios but in RTK I cant.


Solution

  • You should also pass another parameter called formData in RTK Query while passing formdata in API request.

      uploadImage: builder.mutation<any, any>({
      query: (imageFile) => {
        var bodyFormData = new FormData();
        bodyFormData.append('file', imageFile);
        console.log({ bodyFormData, imageFile });
        return {
          url: '/uploader/image',
          method: 'POST',
          headers: {
            'Content-Type': 'multipart/form-data;'
          },
          body: { bodyFormData },
          formData:true           //add this line 👈
        };
      }
    })