Skip to content

Instantly share code, notes, and snippets.

@nbibler
Last active April 11, 2022 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbibler/5f08424bc8411b87acc8e8f906dfdf5d to your computer and use it in GitHub Desktop.
Save nbibler/5f08424bc8411b87acc8e8f906dfdf5d to your computer and use it in GitHub Desktop.
@mswjs/http-middleware behavior mismatch between createServer and createMiddleware
$ curl -X POST -d '{"foo":"bar"}' -H "Content-Type: application/json" http://localhost:9090/user
{"firstName":"John"}
import { createMiddleware } from "@mswjs/http-middleware";
import express from "express";
import { rest } from "msw";
const handlers = [
rest.post("/user", (req, res, ctx) => {
console.log(req.body);
return res(ctx.json({ firstName: "John" }));
}),
];
const app = express();
// app.use(express.json()); // this seems to be required to get data to the handlers?
app.use(createMiddleware(...handlers));
app.listen(9090, () => {
console.log("Server available");
});
{
"name": "msw-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@mswjs/http-middleware": "^0.3.0",
"express": "^4.17.3",
"msw": "^0.39.2"
},
"type": "module"
}
import { createServer } from "@mswjs/http-middleware";
import { rest } from "msw";
const handlers = [
rest.post("/user", (req, res, ctx) => {
console.log(req.body);
return res(ctx.json({ firstName: "John" }));
}),
];
const app = createServer(...handlers);
app.listen(9090);
$ node middleware.js
Server available
undefined
^C
$ node server.js
{ foo: 'bar' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment