The “@ts-stack/body-parser” package passes the parsing results via a Promise

RMAG news

The package @ts-stack/body-parser is a fork of body-parser – the native ExpressJS package. It is written in TypeScript in ESM format, without support for older versions of Node.js < v20.6.0. To install it, run the following command:

npm install @ts-stack/body-parser

This package parses the body of an HTTP request that has the following types: JSON, Raw, Text, URL-encoded. You can use it as follows:

import http from http;
import { getJsonParser } from @ts-stack/body-parser;

const jsonParser = getJsonParser({ limit: 1kb });

http.createServer(async function (req, res) {
try {
const body = await jsonParser(req, req.headers);
res.statusCode = 200;
res.setHeader(Content-Type, text/plain)
res.write(you posted:n);
res.end(JSON.stringify(body));
} catch (err: any) {
// handling an error
}
});

Alternatively, you can use the BodyParserGroup helper. It is designed for cases when you do not know which parser is needed for a specific route. When creating an instance of the BodyParserGroup class, you can pass options for the corresponding parsers, after which you can use the parse method as follows:

import { BodyParserGroup } from @ts-stack/body-parser;

const bodyParserGroup = new BodyParserGroup({
jsonOptions: config.jsonOptions,
textOptions: config.textOptions,
urlencodedOptions: config.urlencodedOptions,
rawOptions: config.rawOptions,
});

const body = await bodyParserGroup.parse(req, req.headers, {});

Please follow and like us:
Pin Share