In my routes, I have the following:
const reservationSchema = {
body: {
type: 'object',
required: ['in', 'out', 'guests', 'language', 'roomsSelected'],
properties: {
language: {
type: 'string',
},
// ... several other property validations here
}
}
};
fastify.post(
'/api/reservations/:slug',
{ schema: reservationSchema },
reservationsController.addReservation
);
I send the POST request from React like this:
const response = await fetch(process.env.REACT_APP_API_HOSTNAME + '/api/reservations/' + property.slug, {
method: 'POST',
body: JSON.stringify(requestBody)
});
I can see that it is correctly sending JSON when I look at the request:
However I receive the following response:
{
"statusCode":400,
"error":"Bad Request",
"message":"body should be object"
}
Am I missing something to automatically parse the POST body as an object in Fastify so I can validate it using a validation schema? Even in my reservationsController.addReservation()
function I need to manually do JSON.parse()
on req.body
.