mswjs / http-middleware

Spawn an HTTP server from your request handlers or apply them to an existing server using a middleware.

Home Page:https://npm.im/@mswjs/http-middleware

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Doesn't work when used with "express.json" middleware

nnnnat opened this issue · comments

Hey y'all big fan of MSW!

I've been using MSW & http-middleware together to create a mock GraphQL API for a few months & I've recently run into an issue after updating to MSW v0.44.2 & http-middleware v0.5.0. I have a very similar setup to the custom server example in this repo & after updating all GQL operations now seem to pass through & return a 404 "Mock not found".

I've put together a small example that reproduces the issue I'm seeing.

Hey, @nnnnat. Thanks for raising this.

I've taken a quick look and it seems that the body we encode in the middleware results in the encoded "[object Object]" string. When MSW attempts to parse that body, it treats it as a string, so it doesn't pass as a valid GraphQL API request.

I believe the issue is somewhere around here:

body: encodeBuffer(req.body),

If I look at your server, I can see that you use express.json() middleware. It will preserve the JSON request body as an object, and that causes the issue:

https://github.com/nnnnat/msw-middleware-example/blob/22c1a8d1c6f1b600ae14562559ad5c25a9ffe61f/main.js#L8

On the middleware's side, we need to check if the req.body is an object and stringify it in that case, so that encodeBuffer always accepts a plain string.

Released: v0.5.1 🎉

This has been released in v0.5.1!

Make sure to always update to the latest version (npm i @mswjs/http-middleware@latest) to get the newest features and bug fixes.


Predictable release automation by @ossjs/release.