Skip to content

Instantly share code, notes, and snippets.

@prashantdawar
Last active November 30, 2018 07:52
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 prashantdawar/d630374be4744b5124f16e5b5c2cedb7 to your computer and use it in GitHub Desktop.
Save prashantdawar/d630374be4744b5124f16e5b5c2cedb7 to your computer and use it in GitHub Desktop.
Anatomy of an HTTP Transaction in nodejs
/**
* credit: https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/
*/
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
var server = http.createServer();
server.on('request',(req, res) => {
if(req.method === 'POST' && req.url === '/echo'){
const { method, url, headers, rawHeaders } = req;
let body = [];
req.on('error',(err) => {
console.error(err.stack);
res.statusCode = 400;
res.end();
}).on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
res.statusCode = 200;
res.setHeader('Content-Type','application/json');
res.write(JSON.stringify({ body, url, method, headers, rawHeaders,}));
res.end();
});
} else {
res.statusCode = 400;
res.end();
}
}).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