Last active
November 30, 2018 07:52
-
-
Save prashantdawar/d630374be4744b5124f16e5b5c2cedb7 to your computer and use it in GitHub Desktop.
Anatomy of an HTTP Transaction in nodejs
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
/** | |
* 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