http-middleware icon indicating copy to clipboard operation
http-middleware copied to clipboard

fix: parse multipart/form-data requests correctly

Open c0per opened this issue 1 year ago • 5 comments

In current version, multipart form request will throw a parsing error.

This is because createMiddleware() treat req.body as the raw body and pass it to new Request(). But req.body is generated by express.json(), which only parse requests with content-type application/json and leave req.body undefined for other requests (like multipart form).

In the PR, req.body is prepared by express.raw({ type: '*/*' }). It will get a Buffer as the raw body for all the requests and pass it directly to new Request(). json, form, even other binary content types will be untouched by express and handled by user with Request API.

c0per avatar Dec 30 '23 09:12 c0per

This will unfortunately be a breaking change. The must-need express.json() will be replaced by a express.raw({ type: '*/*' }).

I didn't think of a way to avoid a middleware. Express.js doesn't provide any way to access the raw request body but using express.raw()

c0per avatar Dec 30 '23 09:12 c0per

Just spent 2 hours trying to debug why calling req.formData() like in the docs was returning Unexpected end of multipart data 😅 Thank you for contributing.

Let me know if I can be of any help to get this merged and released.

LeBenLeBen avatar Feb 20 '24 12:02 LeBenLeBen

I think a larger default size limit is a good idea. I also changed the createServer() function to accept bodyParser options (optionally).

So for createServer() users, it's not a breaking change. for createMiddleware(), it is breaking. They need to add app.use(express.raw()) manually.

@LeBenLeBen Please review these changes, wish we can merge this one. Thanks :)

c0per avatar Mar 27 '24 01:03 c0per

Hello guys, I got this error today: TypeError: Failed to parse body as FormData..

Is there anything I can do to help?

ernestostifano avatar May 21 '24 17:05 ernestostifano

I've just created an issue to cross-reference this PR: https://github.com/mswjs/http-middleware/issues/47

ernestostifano avatar Jun 17 '24 19:06 ernestostifano