reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.72k stars 1.17k forks source link

RTK form data is not sent to the server #3888

Closed dieriba closed 9 months ago

dieriba commented 11 months ago

I am currently writing a chat app, where user can upload avatar picture, for that I use nestJs and their multer abstraction package, all works well with POSTMAN meaning that I can update file from it, however when trying to upload file from the front-end react app I have error. The back-end server act as file is undefined however by checking the browser request I can see that request with body and content-type set to multipart data was sent, but nothing is received by the server while when sending data through POSTMAN all works just fine

Here the react query mutation that should handle the upload avatar functionality

changeAvatar: builder.mutation<
      BaseServerResponse & {
        data: { message: string; statusCode: number; data: string };
      },
      Blob
    >({
      query: (file) => {
        const formData = new FormData();
        formData.append("avatar", file);
        console.log({ formData, file });
        return {
          url: "/files/upload-avatar",
          method: "POST",
          body: formData,
          formData: true,
          Accept: "*/*",
        };
      },
    }),
derek11798 commented 9 months ago

Did you get a solution? I'm stuck with the same issue but im sending json data in the body and my content type is application/json

dieriba commented 9 months ago

Yep I fixed it, the problem in my case was that file was an array of file, i just switched to file[0] instead of file in the formData.append line. Hope it helps!

derek11798 commented 9 months ago

In my case if i use fetch to hit the api the api call was successful, but if i use rtk mutation for the same api it fails. the server is receiving null in the body but in the browser network tab i was able to see all the parameters in the body

here is my react mutation

export const reactionApi = createApi({ reducerPath: "reaction", baseQuery: fetchBaseQuery({ baseUrl: baseURL, prepareHeaders: prepareHeaders, }), endpoints: (builder) => ({ updateReaction: builder.mutation({ query: (data) => { console.log(data); return { url: "/reaction", method: "POST", body: data, }; }, transformResponse: (response) => { return response; }, transformErrorResponse: transformErrorResponse, }), }), });

dieriba commented 9 months ago

Show me where you call the mutation please

derek11798 commented 9 months ago

I was setting the content-type : application/json manually in the prepare header of the mutation, but rtk query by default sets the content-type to application/json. by removing the manually set content-type in prepare header I was able to get the data in my server

HosseinEnsafi commented 3 weeks ago

not working for me as well . use fetch API or axios instead .