I'm working with express
+ json
body parser. For validation purposes I need to distinguish between
- empty object request body was sent by the user (
{}
) - no request body was sent by the user
as I'm trying to provide reasonable error messages, and in one case I need to instruct the user to add missing fields, while in the other case they might not even be aware that the request body should be sent, and the priority is warning them about this.
This to me seems impossible currently, as the json body parser sets request.body
to {}
in case no request body was provided, reference:
https://github.com/expressjs/body-parser/blob/master/lib/types/json.js#L72
My question is, while using the json body parser, is it possible to detect if the request body was actually sent by the client or not? So how would I implement a function like this:
import { Request } from 'express'
function didTheUserSendRequestBody(request: Request): boolean {
// What do?
}
Which returns true
when my endpoint is hit like this:
curl -X POST http://localhost:5000/foo
-H "Content-Type: application/json"
-d '{}'
And false
for this:
curl -X POST http://localhost:5000/foo