Skip to content

Instantly share code, notes, and snippets.

@mikamboo
Created September 29, 2021 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikamboo/90e5a330498a491caaa4e38f47af2b29 to your computer and use it in GitHub Desktop.
Save mikamboo/90e5a330498a491caaa4e38f47af2b29 to your computer and use it in GitHub Desktop.
NodeJS : Handler POST body using native http createServer
const http = require("http");
const { parse } = require("querystring");
const hostname = "0.0.0.0";
const port = 3000;
const server = http.createServer((req, res) => {
if (req.method === "POST") {
let body = "";
req.on("data", (chunk) => {
// convert Buffer to string
body += chunk.toString();
});
req.on("end", () => {
console.log(parse(body));
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ data: parse(body) }));
});
} else {
res.end("Require POST request");
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment