Last active
February 20, 2024 22:45
-
-
Save graphicbeacon/536e5f8a7f91769e761e3e1b01bac758 to your computer and use it in GitHub Desktop.
How to handle the POST request body without using a framework
This file contains 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 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