Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Last active February 20, 2024 22:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save graphicbeacon/536e5f8a7f91769e761e3e1b01bac758 to your computer and use it in GitHub Desktop.
Save graphicbeacon/536e5f8a7f91769e761e3e1b01bac758 to your computer and use it in GitHub Desktop.
How to handle the POST request body without using a framework
const http = require('http');
const { parse } = require('querystring');
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
collectRequestData(req, result => {
console.log(result);
res.end(`Parsed data belonging to ${result.fname}`);
});
}
else {
res.end(`
<!doctype html>
<html>
<body>
<form action="/" method="post">
<input type="text" name="fname" /><br />
<input type="number" name="age" /><br />
<input type="file" name="photo" /><br />
<button>Save</button>
</form>
</body>
</html>
`);
}
});
server.listen(3000);
function collectRequestData(request, callback) {
const FORM_URLENCODED = 'application/x-www-form-urlencoded';
if(request.headers['content-type'] === FORM_URLENCODED) {
let body = '';
request.on('data', chunk => {
body += chunk.toString();
});
request.on('end', () => {
callback(parse(body));
});
}
else {
callback(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment