Edit: MSW 2.0
Since the release of MSW 2.0, the way you operate with request/response bodies is the same now as you do with Fetch API.
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
setupServer(
http.post('/endpoint', async ({ request }) => {
const data = await request.formData()
const email = data.get('email')
if (email !== '[email protected]') {
return HttpResponse.json({ success: false }, { status: 401 })
}
return HttpResponse.json({ success: true })
})
)
In this example, I read the request body as FormData
. You can also read it as .json()
, .text()
, etc.—those are the regular Request
instance methods.
Learn more about the new version of MSW and also How to migrate from 1.x to 2.x.
MSW 1.0
You should be able to get the req.body.email
value given your request sets the Content-Type: application/json
header. Without the Content-Type header, neither MSW nor your actual server could know what kind of data you're attempting to send (if anything, it can be a binary!). By providing the correct Content-Type header you form a correct request but also let MSW be sure that req.body
should be parsed to an object.
// your-code.js
fetch('https://testlogin.com/api/v1/login', {
method: 'POST',
headers: {
// Adding this header is important so that "req.body"
// is parsed into an object in your request handler.
'Content-Type': 'application/json'
},
body: JSON.stringify({ login: '[email protected]' })
})
// your-handlers.js
rest.post('https://testlogin.com/api/v1/login', (req, res, ctx) => {
const { login } = req.body
if (login !== '[email protected]') {
return res(ctx.status(401), ctx.json({ success: false }))
}
return res(ctx.json({ success: true }))
})
Note how the ctx.status(401)
call is inside the res()
function call. Calling any ctx[abc]
methods outside of res
will result in no effect as they rely on being wrapped in res
.
req.body()
is now deprecated, if your body has JSON data you can usereq.json()
(docs) – Caucus