elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Wretch loses the request body for the PUT, POST, and PATCH methods if it is FormData

am1rb opened this issue · comments

Hello there. I realized that wretch loses the request body for the PUT, POST, and PATCH methods if the body type is FormData and you pass it directly to the .put(), .post(), or .patch() methods as their first argument.

A sample code to demo the problem:

const requestBody = new FormData()
requestBody.append("field1", "data 1");
 requestBody.append("field2", "data 2");

wretch()
  // here the body is passed as the first argument, and the method does Jasonify it before attaching the data to the request.
  .post(requestBody, "SERVER_URL")

To see the problem in action, please check this sandbox out, and click on the red button. As you see, the Content-Type value is wrong, and there is nothing in the parsedBody.

We know that the native fetch API supports FormData, and I think that, since wretch is supposed to be a wrapper around it, the .put(), .post(), and .patch() methods need to support FormData inputs.

To address the issue, we need to update this line to exclude FormData objects:
https://github.com/elbywan/wretch/blob/master/src/core.ts#L95
Maybe something like:

const jsonify = (body instanceof FormData)===false && typeof body === "object" && (!base._options.headers || !contentType || isLikelyJsonMime(contentType))