posva / mande

<700 bytes convenient and modern wrapper around fetch with smart extensible defaults
https://mande.esm.is
MIT License
1.2k stars 42 forks source link

Sending FormData does not update Content-Type header to multipart/form-data #447

Closed ArchiDevil closed 10 months ago

ArchiDevil commented 10 months ago

Trying to send file to a backend, right now it is now possible without overriding defaults. Sending FormData using the following code does not set Content-Type header to the correct value. It is application/json instead of multipart/form-data; boundaries=....

  const element = input.value as unknown as HTMLInputElement
  const attachedFile = element.files![0]

  const formData = new FormData()
  formData.append('file', attachedFile)
  const api = apiAccessor(props.url)
  await api.post('', formData)

When content type is set forcefully to multipart/form-data not every backend server could interpret data correctly without boundaries=... set automatically by the browser.

The current workaround is to drop defaults from mande and send files w/o content type set, it seems.

ArchiDevil commented 10 months ago

The workaround I use is the following:

const uploadFile = async () => {
  const element = input.value as unknown as HTMLInputElement
  const attachedFile = element.files![0]

  const formData = new FormData()
  formData.append('file', attachedFile)
  const defaultHeaders = defaults.headers
  try {
    const api = apiAccessor(props.url)
    defaults.headers = {}
    const response = await api.post('', formData)
  } catch (error) {
    console.error(error)
  } finally {
    defaults.headers = defaultHeaders
  }
}
ArchiDevil commented 10 months ago

Created a PR to resolve this issue, but I'm not sure if it is a correct solution.

https://github.com/posva/mande/pull/448