infinitered / apisauce

Axios + standardized errors + request/response transforms.
MIT License
2.78k stars 184 forks source link

doesn't support formData #299

Closed NickeNicrad closed 6 months ago

olignyf commented 1 year ago

I do this if it's any help

  public upload<T>(
    url: string,
    params?: any,
    config?: AxiosRequestConfig,
  ): Promise<ApiResponse<T>> {
    if (!config) {
      config = {};
    }
    config.headers = { 'Content-Type': 'multipart/form-data' };
    const formData = new FormData();
    Object.keys(params).forEach((el: any) => {
      formData.append(el, params[el]);
    });
    const response = this.api.post<T>(url, formData, config);
    return response;
  }
}
eithe commented 1 year ago

axios v0.27.0 has automatic serialization to FormData, but unfortunately apisauce hasn't been updated to that version.

Edit: This PR would fix that: https://github.com/infinitered/apisauce/pull/288

KeystoneScience commented 1 year ago

here is my workaround to make a general post function that can take form data:

const post = apiClient.post;
apiClient.post = async (url, data, axiosConfig = {}, contentType) => {
  if (contentType === "multipart/form-data") {
    axiosConfig.headers = {
      ...axiosConfig.headers,
      "Content-Type": "multipart/form-data",
    };
    const formData = new FormData();
    Object.keys(data).forEach((key) => {
      formData.append(key, data[key]);
    });
    data = formData;
  }

  const response = await post(url, data, axiosConfig);
  return response;
};
markrickert commented 6 months ago

288 has been merged and should fix this issue.