Extract the request body from JSON, text and urlencoded formats.
Install with npm:
$ npm install use-body
import http from "node:http";
import useBody from "use-body";
// TYPES: json / text / urlencoded
// JSON example
http
.createServer((req, res) => {
useBody(
req,
res,
() => {
console.log("Request body", req.body);
res.end("Working!!!");
},
"json"
);
}) // Default format always will be json, but you can choose between json, text and urlencoded as formats
.listen(3000);
/*
example result:
Request body { email: 'body@usebody.com' }
*/
// Text example
http
.createServer((req, res) => {
useBody(
req,
res,
() => {
console.log("Request body", req.body);
res.end("Working!!!");
},
"text"
);
}) // Default format always will be json, but you can choose between json, text and urlencoded as formats
.listen(3000);
/*
example result:
Request body: some text
*/
// URL encoded example
http
.createServer((req, res) => {
useBody(
req,
res,
() => {
console.log("Request body", req.body);
res.end("Working!!!");
},
"urlencoded"
);
}) // Default format always will be json, but you can choose between json, text and urlencoded as formats
.listen(3000);
/*
example result:
Request body: { user: 'getbody' }
*/
Otavio Rampinelli
Copyright © 2024, Otavio Rampinelli. Released under the MIT License.