Last active
January 17, 2024 15:42
-
-
Save AliSawari/f9d40a8ad779128adc2dedbef6ade662 to your computer and use it in GitHub Desktop.
Simple Body Parser in Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { createServer } = require('http'); | |
const server = createServer((request, response) => { | |
// by default assign maximum of 2KB for Body size if there's no Content-Length | |
let size = Number(request.headers['content-length']) || 2048; | |
let bodyData = Buffer.alloc(size); | |
request.on('data', data => { | |
for (let x = 0; x < size; x++) { | |
bodyData[x] = data[x]; | |
} | |
}) | |
request.on('end', () => { | |
const raw = bodyData.toString(); | |
const realBody = JSON.parse(raw); | |
console.log(realBody); | |
// Empty the Buffer | |
bodyData = null; | |
}) | |
response.statusCode = 200; | |
response.end("OK"); | |
}); | |
server.listen(3000, () => console.log("UP")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment