body
helperREserve offers a method to deserialize a request body.
interface BodyOptions {
ignoreContentLength?: boolean
}
type BodyResult = Promise<Buffer | string | object> & {
buffer: () => Promise<Buffer>
text: () => Promise<string>
json: () => Promise<object>
}
function body (request: IncomingMessage, options?: BodyOptions): BodyResult
Types definition for
body
import { body } from 'reserve'
async function customHandler (request, response) {
const requestBody = await body(request).json()
/* ... */
}
Example of
body
The return of await body(request)
depends on the request headers.
If the content-type
is specified and starts with :
text/plain
: a string
is returnedapplication/json
: an object
is returned (after applying JSON.parse
on the request content).Buffer
is returnedIt is possible to force the return type using :
await body(request).text()
: a string
is returnedawait body(request).json()
: an object
is returnedawait body(request).buffer()
: a Buffer
is returned[!CAUTION] If the request’s
content-length
is set (and not ignored through theignoreContentLength
option), the buffer is allocated accordingly.It means the result might be truncated (if too small) or padded with
\x00
(if too large).